1个回答
推荐于2016-10-03
展开全部
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
// 服务端
public class TCPServerDemo {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(5000);
Socket s = ss.accept();
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
ObjectInputStream ois = new ObjectInputStream(in);
SocketMessage message = new SocketMessage();
message.setMessageId(1);
message.setContent("服务器消息1");
oos.writeObject(message);
oos.flush();
SocketMessage temp = (SocketMessage) ois.readObject();
System.out.println("收到客户端消息=" + temp);
}
}
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
// 客户端
public class TCPClientDemo {
public static void main(String[] args) throws Exception{
Socket s = new Socket("localhost", 5000);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
ObjectInputStream ois = new ObjectInputStream(in);
SocketMessage message = new SocketMessage();
message.setMessageId(2);
message.setContent("客户端消息2");
oos.writeObject(message);
oos.flush();
SocketMessage temp = (SocketMessage) ois.readObject();
System.out.println("收到服务端消息=" + temp);
}
}
import java.io.Serializable;
// 消息对象
public class SocketMessage implements Serializable {
private static final long serialVersionUID = 1L;
private String content;
private long messageId;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public long getMessageId() {
return messageId;
}
public void setMessageId(long messageId) {
this.messageId = messageId;
}
@Override
public String toString() {
return getClass().getSimpleName() + "[id=" + getMessageId() + ",content=" + getContent() + "]";
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询