是的,我確實看過關於sun的教程,他們在我的情況下沒有幫助,只傳遞了第一條命令。如何通過Java中的套接字傳輸整數或字節數組
I`ve得到了一個方法
public void openConnection() throws IOException{
serverSocket = new ServerSocket(5346);
Socket simSocket = serverSocket.accept();
is = simSocket.getInputStream();
os = simSocket.getOutputStream();
writer = new PrintWriter(os);
isReader = new InputStreamReader(is);
reader = new BufferedReader(isReader);
System.out.println("Connection succesfull.");
}
和
public void sendTo(int command) {
try {
writer.println(command);
writer.flush();
} catch(Exception e) {
System.out.println("Error sending command to the robot");
System.out.println(e.toString());
}
}
在發送側
,和
public static void setUpConnection() {
try {
socket = new Socket(InetAddress.getLocalHost(), 5346);
is = new InputStreamReader(
socket.getInputStream());
reader = new BufferedReader(is);
writer = new PrintWriter(socket.getOutputStream());
System.out.println("Simulator: connection succesful");
} catch (IOException e) {
e.printStackTrace();
}
}
和
while (true) {
intCommand = reader.read();
ett = reader.readLine(); // does nothing, but without this line it doesn't work
command = (char) intCommand;
在接收端。它可以完美地發送字符或字符的ascii數字。我需要的是改變這個代碼發送整數或簡單的字節數組而不是字符。如果我只是簡單地離開InputStream和OutputStream,它會接收到第一個命令,而這些方法不斷接收通過sendTo發送的內容。即使在套接字文檔中,它們也只能用於發送字符。
看看序列化(創建一個實現可序列化的類或使用其中一個可用的serializaton API)。 – theglauber