我是一个非常初级的Java开发人员(准确地说是想开发的人),并且我尝试使用Youtube教程作为参考来学习Java套接字。我的代码似乎与视频中的所有内容都匹配(变量名称除外),但是,当尝试运行服务器然后运行客户端套接字时,我得到了一个:
Exception in thread "main" java.net.BindException: Address already in use (Bind failed)
我甚至尝试打印local port
只是为了确保我连接到正确的可用端口,但是没有任何效果。我可以参考任何文档来解决此问题吗?或任何指导?
这是我到目前为止的代码:
Server.java
public class serverSocket {
public static void main(String args[]) throws IOException{
String message, serverResponse;
ServerSocket serverSocket = new ServerSocket(56789);
System.out.print(serverSocket.getLocalPort());
Socket acceptClientRequestSocket = serverSocket.accept();
Scanner serverScanner = new Scanner(acceptClientRequestSocket.getInputStream());
message = serverScanner.next();
System.out.println(message);
serverResponse = message.toUpperCase();
PrintStream newMessage = new PrintStream(acceptClientRequestSocket.getOutputStream());
newMessage.println(serverResponse);
}
}
Client.java
public class clientSocket {
public static void main(String args[]) throws UnknownHostException, IOException {
String message,outputMessage;
Scanner clientInput = new Scanner(System.in);
Socket clientSocket = new Socket("localhost",56789);
Scanner incomingStream = new Scanner(clientSocket.getInputStream());
System.out.println("Enter a message");
message = clientInput.next();
PrintStream printClientStream= new PrintStream(clientSocket.getOutputStream());
printClientStream.println(message);
outputMessage = incomingStream.next();
System.out.println(outputMessage);
}
}