两个客户端通过TTP服务器开始通信。第一个基本问题是消息,因为各种消息总是根据来自不同主机的反馈而具有不同的结构。我考虑过使用带有套接字TPC的LinkedList。
//服务器
public static void main (String[]args) throws Exception {
final int port=12345;
try {
ServerSocket serversocket=new ServerSocket(port);
System.out.println("TTP on-line")
while (true) {
Socket clientSocket=serversocket.accept();
System.out.println("accept "+clientSocket.getInetAddress().getHostName()+" on port "+clientSocket.getPort());
ObjectOutputStream outToClient = new ObjectOutputStream(clientSocket.getOutputStream());
ObjectInputStream inFromClient = new ObjectInputStream(clientSocket.getInputStream());
LinkedList<Message> inList = new LinkedList<>();
Message inMsg = null;
inList =(LinkedList<Message>)inFromClient.readObject();
inMsg = inList.pop();
/* Send the modified Message object back */
outToClient.writeObject(inMsg);
}
}
catch (Exception e) {
System.err.println("Server Error: " + e.getMessage());
System.err.println("Localized: " + e.getLocalizedMessage());
System.err.println("Stack Trace: " + e.getStackTrace());
System.err.println("To String: " + e.toString());
//客户端
public static void main(String[] args) throws Exception {
final int port=12345;
System.out.println("Client Started...");
try {
Socket clientSocket = new Socket("127.0.0.1", port);
ObjectOutputStream outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
ObjectInputStream inFromServer = new ObjectInputStream(clientSocket.getInputStream());
LinkedList<Message> msgList = new LinkedList<>();
Message msg = new Message();
msg.setIp //make
msgList.push(msg);
// Send the Message Object to the server
outToServer.writeObject(msgList);
// Retrive the Message Object from server
LinkedList<Message> inFromServerList = new LinkedList<>();
Message msgFrmServer = null;
inFromServerList = (LinkedList<Message>)inFromServer.readObject();
msgFrmServer = inFromServerList.pop();
//Print out the recived Message
msgFrmServer.getMessage();
clientSocket.close();
}
catch (Exception e) {
System.err.println("Client Error: " + e.getMessage());
System.err.println("Localized: " + e.getLocalizedMessage());
System.err.println("Stack Trace: " + e.getStackTrace());
问题是对象列表的强制转换对象....
//消息
public class Message implements Serializable {
private String ipTTp;
private String ipM;
private String ipD;
public Message ( String ipT, String ipMit, String ipDest) {
this.ipTTp= ipT;
this.ipM=ipMit;
this.ipD=ipDest;
}
public Message ( ) {
}
public void setIpm (String ipm) {
this.ipM=ipm;
}
public void setIpdes (String ipd) {
this.ipD=ipd;
}
public void getMessage () {
System.out.println("ip mit: "+ipMi);
System.out.println("ip dest: "+ipDest);
}
我该怎么办?我错过了问题的逻辑?我试图序列化Message类,但我总是收到警告。我声明我不是专家java ...