简体   繁体   中英

Java Socket Programming - Address already in use (errno=98)

I'm try to write a basic server-client java application. However, I alway got a message of "socket bind on 10 for port 13244 failed: Address already in use (errno=98)" error no matter what port I'm using.

I have attach a source code of my application, just wondering is there very stupid mistake I'm making.

Many Thanks!

Cheers, J

/**
 * Command process test.
 */

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

public class CommandProcessTest implements Runnable{
  private static final int PORT = 13244;
  private ServerSocket serverSocket;

  public static void main(String[] args) {
    CommandProcessTest test = new CommandProcessTest();

    System.out.println("starting server.");
    test.start();
    System.out.println("server start up.");

//     try {
//       test.wait(100);
//     } catch(InterruptedException e) {
//     }


//     Thread client = new Thread(test);

    System.out.println("Server start receiving.");
    test.start();
    System.out.println("Server exit.");
  }

  private void start() {
    try {
      serverSocket = new ServerSocket(PORT);
    } catch (IOException e) {
      System.out.println("Could not listen on port: 4444");
      System.exit(-1);
    }
  }

  private void server() {
    Socket clientSocket = null;

    try {
      clientSocket = serverSocket.accept();
      CommandProcess cp = new CommandProcess(clientSocket);

      int cmd = 10;
      String arg = "";
      cp.sendCommand(cmd);

      arg = "hello";
      cp.sendCommand(cmd, arg.split(" "));

      arg = "hello world";
      cp.sendCommand(cmd, arg.split(" "));

      arg = "world hello world";
      cp.sendCommand(cmd, arg.split(" "));

    } catch (IOException e) {
      System.out.println("Accept failed: 4444");
      System.exit(-1);
    }
  }

  private void client() {
    try {
      Socket socket = new Socket("localhost", PORT);
      CommandProcess cp = new CommandProcess(socket);

      while(true) {
        int cmd = cp.getCommand();
        String[] args = cp.getArguments();

        String s = "Command: " + Integer.toString(cmd);
        if(args != null) {
          for(int i = 0; i < args.length; i++) {
            if(args[i] == null) {
              break;
            }
            s += args[i];
          }
        }

        System.out.println(s);
      }

    } catch(IOException e) {
      System.out.println("Would not connect to local host: 444");
      System.exit(-1);
    }
  }

  public void run() {
    System.out.println("Starting client");
    client();
    System.out.println("Client startup.");
  }
}

You do start() twice. You cannot start two servers listening on the same port.

你调用test.start()两次,第二次会失败,因为第一次抓住套接字。

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