NOTE for socket:
- Socket can not be use to read and send at the same time
- Only one state can be use in socket, client state send - server state read or vise versa.
- At server side, maintain state read and send for each connection accepted by serversocket.
Swing JFrame to start server and client
package com.dedetok;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JButton;
public class Test extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
MyServerThread myServerThread;
ExecutorService executor;
MyClient myClient=null;
/**
* Create the frame.
*/
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JButton btnStartServer = new JButton("Start Server");
contentPane.add(btnStartServer);
btnStartServer.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
//System.out.println("Test"); // debug
// TODO Auto-generated method stub
if (executor==null) {
executor = Executors.newSingleThreadExecutor();
try {
if (myServerThread==null) {
System.out.println("Server null, create new"); // debug
myServerThread = new MyServerThread();
executor.submit(myServerThread);
}
//System.out.println("create thread"); // debug
//System.out.println("run thread"); // debug
if (executor.isTerminated()) {
System.out.println("is terminated"); // debug
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
JButton btnStartClient = new JButton("Start Client");
contentPane.add(btnStartClient);
btnStartClient.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try {
/*
if (myClient== null) {
myClient = new MyClient();
}
myClient.sendCommand();
*/
myClient = new MyClient();
myClient.sendCommand();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
}
}
Server part
package com.dedetok;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServerThread implements Runnable {
ServerSocket myServerSocket;
//InetAddress myServerInetAddress;
int myServerPort = 54321;
public MyServerThread() throws IOException {
myServerSocket = new ServerSocket(myServerPort);
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
Socket myClientSocket;
try {
myClientSocket = myServerSocket.accept();
/*
InetAddress inetAddress = myClientSocket.getInetAddress();
System.out.println("receive from client: "+inetAddress.toString()); // debug
InputStream myInputStream = myClientSocket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(myInputStream);
String sClient;
sClient = (String) ois.readObject();
System.out.println("From Client: "+sClient); // debug
sClient = "Echo: "+sClient;
OutputStream myOutputStream = myClientSocket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(myOutputStream);
oos.writeObject(sClient);
oos.flush();
//ois.close();
//oos.close();
myClientSocket.close();
*/
ClientHandler clientHandler = new ClientHandler(myClientSocket);
clientHandler.run();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ClientHandler implements Runnable {
Socket socket;
ClientHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
// TODO Auto-generated method stub
InetAddress inetAddress = socket.getInetAddress();
System.out.println("receive from client: "+inetAddress.toString()); // debug
InputStream myInputStream;
try {
myInputStream = socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(myInputStream);
OutputStream myOutputStream = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(myOutputStream);
boolean loopMsg = true;
while (loopMsg) {
String sClient = (String) ois.readObject();
if (sClient.equals("END")) {
loopMsg = false;
}
System.out.println("From Client: "+sClient); // debug
sClient = "Echo: "+sClient;
oos.writeObject(sClient);
oos.flush();
}
//ois.close();
//oos.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Client part
package com.dedetok;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyClient {
ExecutorService executor;
boolean isRun = false;
public MyClient() throws IOException {
executor = Executors.newSingleThreadExecutor();
}
public void sendCommand() {
if (!isRun) {
executor.submit(myRun);
isRun = true;
}
}
int i=0;
String str = "Hello ";
Runnable myRun = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//System.out.println("Running thread client"); // debug
try {
/*
System.out.println("create socket"); // debug
Socket mySocket = new Socket("127.0.0.1", 54321);
OutputStream myOutputStream = mySocket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(myOutputStream);
System.out.println("send "+i); // debug
oos.writeObject("END");
oos.writeObject(str+1);
oos.flush();
InputStream myInputStream = mySocket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(myInputStream);
System.out.println("receive "+i); // debug
String rStr = (String) ois.readObject();
System.out.println(rStr); // debug
System.out.println("end client"); // debug
//mySocket.close();
//ois.close();
//oos.close();
mySocket.close();
i++;
*/
System.out.println("create socket"); // debug
Socket mySocket = new Socket("127.0.0.1", 54321);
OutputStream myOutputStream = mySocket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(myOutputStream);
InputStream myInputStream = mySocket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(myInputStream);
while (i<10) {
String str = "send "+i;
System.out.println(str); // debug
if (i==9)
str="END";
oos.writeObject(str);
oos.flush();
System.out.println("receive "+i); // debug
String rStr = (String) ois.readObject();
System.out.println(rStr); // debug
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//mySocket.close();
//ois.close();
//oos.close();
i++;
}
mySocket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
isRun = false;
}
};
}
No comments:
Post a Comment