我已经阅读了Stack-overflow中大多数类似的问题。但我无法找到类似的。 我构建了一个客户端和一个服务器。对于我的客户端网络,我构建了一个包含套接字和许多相关方法的类:
public class Connector {
private Socket socket;
private DataOutputStream output;
private DataInputStream input;
public Connector(int x) throws UnknownHostException, IOException{
socket=new Socket("localhost",x);
}
public boolean isConnected(){
return socket.isConnected();
}
public void sendInfo(String str) throws IOException{
output = new DataOutputStream(socket.getOutputStream());
output.writeUTF(str);
output.flush();
}
public String receiveInfo() throws IOException{
input = new DataInputStream(socket.getInputStream());
return input.readUTF();
}
public boolean loginSuccess() throws IOException{
input = new DataInputStream(socket.getInputStream());
return input.readBoolean();
}
}
当我的客户端运行时(服务器在我的IDE中运行),
String userAccount = "VerifyAccount" + "@" + userNametf.getText() + "@" + passwordtf.getText() + "@" + i;
connector.sendInfo(userAccount);
if(connector.isConnected())
System.out.println("the connector is still connected!");
else
System.out.println("the connector is no connected!");
if(connector.loginSuccess()){
System.out.println("Log in success");
}
else;
这是我的服务器:
ServerSocket serverSocket = new ServerSocket(8000);
while(true){
Socket socket = serverSocket.accept();
Thread thread = new Thread(()->{
try{
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
String tempStr = input.readUTF();
System.out.println("Server receive data : "+tempStr);
String[] tempStrArray = tempStr.split("@");
if(tempStrArray[0].equals("VerifyAccount")){
if(UserVerification.isValid(tempStr.substring(14))==1){
output.writeBoolean(true);
output.flush();
}
else{}
}
else if(tempStrArray[0].equals("RegisterAccount")){}
else{}
}
catch(IOException ex){
ex.printStackTrace();
}
});
thread.start();
}
所以整个过程是客户端套接字连接到服务器套接字, 然后客户端向服务器发送一个字符串,服务器处理字符串,并将一个布尔值写回客户端,但是当我调用connector.LoginSuccess()时,编译器将抛出这样的异常:enter image description here < / p>
答案 0 :(得分:0)
您永远不会关闭已接受的套接字。您还尝试读取可能永远不会发送的布尔值。而且,正如我在评论中所说,isConnected()
没有按照你的想法做到:当对等方断开连接时,它不会神奇地开始返回false。