【问题标题】:Java Socket Programming - Address already in use (errno=98)Java 套接字编程 - 地址已在使用中 (errno=98)
【发布时间】:2009-05-12 13:51:20
【问题描述】:

我正在尝试编写一个基本的服务器-客户端 java 应用程序。但是,无论我使用什么端口,我总是收到“10 端口 13244 的套接字绑定失败:地址已在使用 (errno=98)”错误消息。

我附上了我的应用程序的源代码,只是想知道我是否犯了非常愚蠢的错误。

非常感谢!

干杯, 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.");
  }
}

【问题讨论】:

    标签: java sockets


    【解决方案1】:

    你做了两次start()。您不能启动两个在同一个端口上侦听的服务器。

    【讨论】:

    • 我想你只比我快几秒钟。 +1。
    【解决方案2】:

    你调用了两次test.start(),第二次会失败,因为第一次抢了socket。

    【讨论】:

    • 确实,几秒钟……+1 ;-)
    猜你喜欢
    • 2018-01-30
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 2021-05-14
    • 2015-06-04
    相关资源
    最近更新 更多