套接字readInt不总是工作

套接字readInt不总是工作

问题描述:

我正在构建一个客户端 - 服务器Java应用程序。问题是,当我用writeInt()发送Integer时,有时会阻塞readInt()。套接字readInt不总是工作

客户

PrintWriter socketOut = new PrintWriter(sock.getOutputStream()); 
DataOutputStream d = new DataOutputStream(sock.getOutputStream()); 
String s = "User"; 
socketOut.println(s); 
socketOut.flush(); 
d.writeInt(data[0]); 
d.flush(); 
d.writeInt(data[1]); 
d.flush(); 

服务器

while(true){ 
     System.out.println("Listening for clients..."); 
     clientSock = serverSock.accept(); 
     Scanner in = new Scanner(clientSock.getInputStream()); 

     String clientType = in.nextLine(); 

     switch(clientType){ 
      case "Resource": 
       new Thread(new ResourceService(clientSock)).start(); 
       break; 
      case "User": 
       new Thread(new UserService(clientSock)).start(); 
       break; 
     } 

    } 

用户线程

@Override 
    public void run(){ 
     try{ 
     DataInputStream input = new DataInputStream(user.getInputStream()); 
     int i = 0; 
     int a = input.readInt(); // Sometimes it blocks here. 
     int b = input.readInt(); 
     System.out.println(a); 
     System.out.println(b); 
     ... 

我试图根据发送到服务器的第一个字符串客户端之间的区别。有时服务器读取整型,有时会阻塞。 的输出的例子是:

Listening for clients... 
Listening for clients... 
Listening for clients... 
Listening for clients... 
Listening for clients... 
1      // here the server didn't block 
100000 
Listening for clients... 

可能不是一个好主意,使用DataInputStream类/ DataOutputStream类与扫描仪和PrintWriter的混合在一起。建议使用Scanner和PrintWriter来进行用户交互。

尝试只使用DataOutputStream和DataInputStream。

客户

DataOutputStream d = new DataOutputStream(sock.getOutputStream()); 
String s = "User"; 
d.writeUTF(s); 
d.writeInt(data[0]); 
d.flush(); 
d.writeInt(data[1]); 
d.flush(); 

服务器

DataInputStream input = new DataInputStream(clientSock.getInputStream()); 
String clientType = input.readUTF(); 

switch(clientType){ 
    case "Resource": 
     new Thread(new ResourceService(input)).start(); 
     break; 
    case "User": 
     new Thread(new UserService(input)).start(); 
     break; 

网友跟帖

int a = input.readInt(); 
int b = input.readInt(); 
System.out.println(a); 
System.out.println(b); 

注1:DataInputStream类/ DataOutputStream联合使用自己的协议写/读UTF字符串,没有必要使用线路终端。注意2:PrintWriter的方法不会抛出I/O异常,您必须检查调用checkError(可能不是这里的问题)。

+1

它现在有效。谢谢! –