是的,我确实看过关于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