多线程试图让javasocket程序工作,但得到“java.net.BindException:地址已在使用6666”
这是密码
我已经编写了一个服务器和客户端。但当我运行它们时(正如你在上一个程序中看到的),我得到了以下错误:
Whoop s! java.net.BindException: Address already in use 6666
6666是我指定的端口号
import java.net.*;
import java.io.*;
import java.lang.*;
public class processSendHelper
{
Process p;
String address;
int port;
long msg_data;
processSendHelper(int pid, int current_round, long address, long msg_data, int port)
{
try
{
ServerSocket sSoc = new ServerSocket(port);
Socket inSoc = sSoc.accept();
msg_Thread msgT = new msg_Thread(inSoc, msg_data);
msgT.start();
Thread.sleep(5000);
sSoc.close();
}
catch(Exception e)
{
System.out.println("Whoop s! " + e.toString());
}
}
}
/* sends out (or rather just makes available) the provided msg
* */
class msg_Thread extends Thread
{
Socket threadSoc;
long msg_data;
msg_Thread (Socket inSoc, long msg_data)
{
threadSoc = inSoc;
this.msg_data = msg_data;
}
public void run()
{
try
{
PrintStream SocOut = new
PrintStream(threadSoc.getOutputStream());
SocOut.println(msg_data);
}
catch (Exception e)
{
System.out.println("Whoops!" + e.toString());
}
try
{
threadSoc.close();
}
catch (Exception e)
{
System.out.println("Oh no! " +
e.toString());
}
}
}
import java.net.*;
import java.io.*;
public class processReceiveHelper
{
Socket appSoc;
BufferedReader in;
String message;
String host;
int port;
processReceiveHelper(String host,int port)
{
try
{
appSoc = new Socket(host,port);
in = new BufferedReader(new InputStreamReader(appSoc.getInputStream()));
message = in.readLine();
System.out.println(message);
/* Tokenizer code comes here
* Alongwith the code for
* updating the process object's
* data
* */
}
catch (Exception e)
{
System.out.println("Died... " +
e.toString());
}
}
}
public class Orchestrator
{
public static void main(String[] args)
{
processSendHelper psh = new processSendHelper(1, 2, 1237644, 6666, 2002);
processReceiveHelper prh = new processReceiveHelper("localhost", 2002);
}
}
编辑:
我发现了问题。原因是我从同一个主程序运行服务器和客户端
以下措施奏效了:
# 1 楼答案
这意味着已经有一个应用程序在端口6666上运行,阻止您的Java应用程序使用它。然而,同样可能的是,您的Java应用程序仍有一个正在运行的进程保持在6666上。终止任何正在运行的java进程,并尝试重新运行代码——如果仍然失败,那么您有其他一些应用程序使用6666,您最好使用其他端口