这是代码
我已经写了一个服务器和客户端。但是当我运行它们时(正如您在上一个程序中看到的那样),我收到以下错误:
哎呀! java.net.BindException:地址已在使用 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);
}
}
编辑:
我发现了问题。原因是我从同一个主程序运行服务器和客户端。
以下工作有效:
最佳答案
这意味着已经有一个应用程序在端口 6666 上运行,阻止您的 Java 应用程序使用它。然而,同样可能的是,您的 Java 应用程序的正在运行的进程仍然保留在 6666 上。终止任何正在运行的 java 进程并尝试重新运行代码 - 如果仍然失败,那么您有其他应用程序使用 6666,您会更好使用不同的端口。
关于java - 尝试让 java 套接字程序工作,但得到 "java.net.BindException: Address already in use 6666 ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9551139/