我有一个有趣的问题。我正在尝试建立对等连接,这意味着客户端进程既充当服务器又充当客户端。理想情况下,它应该有一个客户端套接字(Socket 类)和一个服务器套接字(Server Socket 类)。现在我尝试使用这个概念,但它不起作用。请看一下:
public static void main(String argv[]) throws Exception
{
Socket clientSocket = null;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Enter the server port u want to be assigned to this peer:");
sentence = inFromUser.readLine();
System.out.println("writing current port to client = "+ sentence);
outToServer.writeBytes("p~"+sentence + "\n" );
int serverport = Integer.parseInt(sentence);
ServerSocket server = new ServerSocket(serverport);
Socket client;
//client
System.out.println("enter port no of the server port of an other peer:");
int msg=Integer.parseInt(inFromUser.readLine());
clientSocket = new Socket("localhost", msg);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("hi");
while(true)
{
//server port listens infinitely and spawns new thread
System.out.println("inside true");
client = server.accept();
Thread serverThread = new Thread(new acceptconnection1(client));
serverThread.start();
}}}
class acceptconnection1 implements Runnable {
BufferedReader inFromClient, inn;
DataOutputStream ds;
Socket socket;
int peersocket;
String clientSentence;
int serverport ;
Socket clientSocket = null;
acceptconnection1 (Socket socket,) throws IOException{
this.socket = socket;
inn = new BufferedReader (new InputStreamReader(System.in));
inFromClient =new BufferedReader(new InputStreamReader(socket.getInputStream()));
ds = new DataOutputStream(socket.getOutputStream());
}
@Override
public void run () {
String cs,a;
try {
System.out.println("waiting for connection ");
if(( clientSentence = inFromClient.readLine())!=null)
{
System.out.println("Message from other peer" + clientSentence);
}
} catch (IOException ex) {
Logger.getLogger(acceptconnection1.class.getName()).log(Level.SEVERE, null, ex);
}}}
输出:当我创建两个客户端进程时,
o / p of client1:输入您要分配给此对等方的服务器端口:1111将当前端口写入客户端= 1111 hi输入您要连接的端口号:2222 inside true inside true等待连接
输入您要分配给此对等方的服务器端口:2222 将当前端口写入客户端 = 2222 hi 输入您要连接的端口号:1111 inside true inside true 等待连接
发生的事情是他们都在等待连接。我该如何解决这个问题?