3

我试图让两个人连接到服务器,并且服务器在他们之间建立连接。然后他们可以互相交谈。如果你看到说“HEREEEEEEEEEEEEEEEEEE”的评论,我有一个thread.sleep,出于某种奇怪的原因,它与thread.sleep()一起工作,但是如果我把它拿出来,如果有的话,只有一个人可以发送给他们的伙伴没有thread.sleep();

PS它也可以使用System.out.println,而不仅仅是thread.sleep

我还有更多文件要处理,但是加载它们很痛苦,并且希望这是人们知道的常见问题。

任何帮助表示赞赏。

import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;

public class ConnectedClient extends Thread
{

  private Socket cSocket;       //Client's Socket
  private PrintWriter cout;     //write to Client
  private BufferedReader cin;   //Read from Client
  private String cip;           //Clients IP

  private Socket pSocket;       //Partner's Socket
  private PrintWriter pout;     //Write to partner
  private String pip;           //Partner's ip

  private Server srvr;          //Current server

  public ConnectedClient(Socket skt, Server s)
  {
    try
    {
      //Client information
      cSocket = skt;
      cout = new PrintWriter(cSocket.getOutputStream(), true);
      cin = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
      //Partner's information
      pSocket = null;
      pip = null;
      pout = null;

      //Server and thread
      srvr = s;
      start();
    }
    catch(Exception E)
    {
      System.out.println(E);
    }
  }

  public void run()
  {
    String data;
    System.out.println("Connected to client");
    try
    {
      //Get the ip address and add it to server's table
      while(!cin.ready()){}
      cip = cin.readLine();
      srvr.addToIpTable(cip, cSocket);

      ////Waiting for another client//
      while(pSocket == null) {Thread.sleep(10);} // HEREEEEEEEEEEEEEEEEEEEEE
      System.out.println("Found a partner");
      pout = new PrintWriter(pSocket.getOutputStream(), true);
      System.out.println("I am here");
      cout.println("Done");

      while(true)
      {
        //Waits for a message
        while(!cin.ready()){}
        data = cin.readLine();

        //Outputs message to partner
        pout.println(data);
        pout.flush();
        //End when exit is typed
        if(data.equals("exit"))
          break;
      }

      //Cleanup
      cSocket.close();
      pSocket.close();
      cout.close();
      cin.close();
    }
    catch(Exception E)
    {
      System.out.println(E);
    }
  }


  public String getCip()
  {
    return cip;
  }

  public Socket getCSocket()
  {
    return cSocket;
  }

  public void setPartner(String partnerIp, Socket socket)
  {
    pip = partnerIp;
    pSocket = socket;
  }
}
4

1 回答 1

5

尝试使 pSocket 易失 - 在繁忙的等待期间,它将在缓存中,并且当其他线程更改它时永远不会更新。

您可能仍然想要一个小睡眠,以避免在等待时 100% 使用核心。

于 2012-11-08T23:10:00.117 回答