客户端代码:
服务器段代码:
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class TCPClient extends Thread{
@Override
public void run() {
Scanner reader = new Scanner(System.in);
while (true) {
System.out.println("输入Message的ID");
int id = reader.nextInt();
System.out.println("请输入Message的内容");
String content = reader.next();
Message msg = new Message(id,content);
try {
Socket socket = new Socket("127.0.0.1", 8802);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(msg);
out.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
服务器段代码:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer extends Thread{
@Override
public void run() {
try {
ServerSocket mServerSocket = new ServerSocket(8802);
Socket mSocket;
while (true) {
mSocket = mServerSocket.accept();
ObjectInputStream in = new ObjectInputStream(mSocket.getInputStream()) ;
Message message = (Message) in.readObject();
System.out.println(message);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}