我遇到了一些愚蠢的问题,我不知道我在做什么错。
我写了客户端和服务器,客户端工作正常。我检查了输出流在客户端中是否正常工作,有字节,但是在服务器中,当客户端连接时,方法 in.avaible() 总是返回零?为什么?
我的服务器的一些代码:
try{
serverSocket = new ServerSocket(port);
}
catch (IOException e){
System.err.println("Could not listen on port: " + port);
return false;
}
System.out.println("Server Started");
txtServer.setText("Server wystartował");
return true;
}
else{
txtPort.setText("Brak Portu!");
txtPort.setBorder( BorderFactory.createLineBorder(Color.RED) );
return false;}
}
@Override
public void run() {
try{
clientSocket = serverSocket.accept();
data.clear();
System.out.println("Client connected");
cl_obs = new Client_obs(clientSocket, data);
Thread t = new Thread(cl_obs);
t.start();
}
catch (IOException e){
System.err.println("Accept failed.");
System.exit(1);
}
}
package Server;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class Client_obs implements Runnable {
private InputStream in;
private data data;
private Socket clientSocket = null;
public Client_obs(Socket cl, data data1){
clientSocket =cl;
data = data1;
}
@Override
public void run() {
try {
in = clientSocket.getInputStream();
byte[] data1 = new byte[in.available()];;
for (int i=0; i<data1.length; i++){
data1[i] = (byte)in.read();
}
data.setData(data1);
data.displayMSG(data.getdata());
in.close();
clientSocket.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}