[英]How to transfer integer or byte array through socket in java
是的,我确实看过有关sun的教程,但在我的情况下它们没有帮助,只是传递了第一个命令。
我有办法
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码。 我需要更改此代码以发送整数或仅发送字节数组而不是char。 如果我只留下InputStream和OutputStream,它确实会收到第一个命令,也就是它,而这些方法不断接收通过sendTo发送的内容。 即使在套接字文档中,它们也仅具有仅发送字符的示例。
只需对服务器进行编码,即可将接收到的值存储为int而不是char。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.