简体   繁体   中英

Java Client Server Socket Error: java.net.BindException: Address already in use: bind

This is the server side code I'm pretty sure the error is that the Server Socket Isn't closing the port? There is no problem when I run the program but, When I run it again I get this Error:

Exception in thread "main" java.net.BindException: Address already in use: bind
    at java.base/sun.nio.ch.Net.bind0(Native Method)
    at java.base/sun.nio.ch.Net.bind(Net.java:550)
    at java.base/sun.nio.ch.Net.bind(Net.java:539)
    at java.base/sun.nio.ch.NioSocketImpl.bind(NioSocketImpl.java:643)
    at java.base/java.net.ServerSocket.bind(ServerSocket.java:396)
    at java.base/java.net.ServerSocket.<init>(ServerSocket.java:282)
    at java.base/java.net.ServerSocket.<init>(ServerSocket.java:173)
    at internet.server.main(server.java:11)

But if I change the port number it fixes for that one time running. Someone please help also I haven't learned java server sockets or client sockets yet soo I need help as far as I know no one else is having this problem

package internet;

import java.io.IOException;
import java.net.*;
import java.io.*;

public class server {

    public static void main(String[] args) throws IOException {
        println("Compiled");
        ServerSocket ss = new ServerSocket(5502);
        Socket s = ss.accept();
        println("Client Connected!");
        InputStreamReader in = new InputStreamReader(s.getInputStream());
        BufferedReader bf = new BufferedReader(in);
        String str = bf.readLine();
        println("Client: " + str);
        
        s.close();
        ss.close();
            
    }
    
    public static void println(String args) {
        System.out.println(args);
    }
}

This will works fine as long as you terminate your previous execution before you re run it.

Try closing those streams, InputStreamReader and BufferedReader as well. Close them before socket and ServerSocket.

bf.close();
in.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM