客户端既作为客户端又作为服务器 - JAVA

时间:2012-09-21 07:05:54

标签: java

我有一个有趣的问题。我正在尝试建立对等连接,这意味着客户端进程既充当服务器又充当客户端。理想情况下,它应该有一个客户端套接字(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);
    }}}

输出: 当我创建两个客户端进程时,

客户1的o / p: 输入您希望分配给此对等方的服务器端口: 1111 将当前端口写入client = 1111 你输入端口没有你想连接到: 2222 内心真实 内心真实 等待连接

输入您想要分配给此对等方的服务器端口: 2222 将当前端口写入client = 2222 你输入端口没有你想连接到: 1111 内心真实 内心真实 等待连接

他们俩都在等待连接。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您遇到了死锁情况。为此,首先创建ServerSocket,以便Socket可以与之交谈。创建将连接但不接受的Socket。然后接受连接。

BTW:您无需为流量创建两个连接即可双向传递。建立连接后,您可以将该连接用作客户端 - 服务器,服务器 - 服务器或任何连接。