1
我正在構建一個客戶端 - 服務器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...
它現在有效。謝謝! –