java - BindException:地址已在使用中
问题描述
我正在尝试使用 Java 进行套接字编程。为了让事情顺利进行,我尝试了一个非常简单的服务器和客户端代码片段,如下所示
public class Server {
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
public Server(int port) {
// starts server and waits for a connection
while (true) {
try{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
in.close();
}
catch(IOException i){
System.out.println(i);
}
}
}
public static void main(String args[]) {
new Server(5000);
}
}
Client.java 如下所示
public class Client {
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public Client(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}// string to read message from input
String line = "";
// keep reading until "Over" is input
while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
// close the connection
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[]) {
Client client = new Client("127.0.0.1", 5000);
}
}
它适用于与客户端的第一次连接。一旦客户端发送Over server 开始给出异常java.net.BindException: Address already in use
。
即使我正在关闭套接字,为什么端口正在使用中?
解决方案
以下代码行试图ServerSocket
在端口上再次创建(实际上是无数次),5000
这就是您收到错误的原因。
while (true) {
try{
server = new ServerSocket(port);
执行以下操作:
try{
server = new ServerSocket(port);
}catch(IOException i){
System.out.println(i);
}
while (true) {
try{
推荐阅读
- python - 通过部分学习 Python 并发
- angular - 激活路由时如何在组件初始化的同时进行操作
- python - 为什么是 q.join() 而不是 t.join()?
- matlab - 求解具有自由度的符号方程组
- javascript - Cloudinary 不适用于 WebStorm
- haproxy - HAProxy 代理转发到外部 HTTPS,带有 URL 重写
- sql - SQL如何确定多列唯一索引的唯一性
- python - Python 自动上翻/下翻 Pdf 查看器
- python - 如何将“O”值转换为日期格式
- aws-lambda - Lambda 函数与 Api 网关(反向代理)使用无服务器和 Express