2012-01-26 144 views
0

是的,我确实看过关于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发送的内容。即使在套接字文档中,它们也只能用于发送字符。

+0

看看序列化(创建一个实现可序列化的类或使用其中一个可用的serializaton API)。 – theglauber

回答

0

只需编码您的服务器以将接收到的值存储为int而不是char。

+0

我该如何做到这一点,我认为只是一个什么样的InputStream或smth使用的问题,因为它发送完美的号码,只需要接收它作为一个字节数组,并不尝试从它得到一个字符 – user975869

+0

如果问题在于接收方,那么只需确保方知道来自流的内容,以便它可以将其存储为正确的数据类型。 – bdabmxican

相关问题