お互いに接続するクライアントとサーバーを作成しました。サーバーは、クライアントが(処理後に)クライアントに送り返したメッセージを送信することができます...しかし、2つのクライアントが接続されている場合、最初にメッセージを送ったクライアントにメッセージを送り返すだけです(lol ...)クライアントサーバーの通信障害C#
どのクライアントからどのクライアントにメッセージが送信されるように修正すればよいですか?
は、私は、クライアントとサーバー間の接続を取得するための出発点として、以下の例を使用:私は以下の私のプログラムがフリーズしようとすると:
SERVER:
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception ex)
{
Debug.Print(ex.Message);
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
foreach (TcpClient c in ListOfClients)
{
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
clientStream.Write(message, 0, message.Length);
}
クライアント:
private void boxChatArea_KeyPress(object sender, KeyPressEventArgs e)
{
char[] contentForServer = null;
boxChatArea.MaxLength = 4000;
if (e.KeyChar == (char)Keys.Enter)
{
client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), MainWindow.port);
client.Connect(serverEndPoint);
clientStream = client.GetStream();
contentForServer = boxChatArea.Text.ToCharArray();
byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(contentForServer);
clientStream.Write(bytesToSend, 0, bytesToSend.Length);
clientStream.Flush();
boxChatArea.Text = null;
StartListening();
}
}
public void StartListening()
{
HandleServerComm(client);
}
private void HandleServerComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
bytesRead = 0;
try
{
//FREEZES HERE - it doesn't freeze here without the loop that we added within the server...
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception ex)
{
Debug.Print(ex.Message);
//break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
}
if (bytesRead != 0)
{
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
string text = (encoder.GetString(message, 0, message.Length));
if (enterCount >= 1)
{
displayBoxChatArea.AppendText(Environment.NewLine);
displayBoxChatArea.AppendText(text);
//displayBoxChatArea.Text = text;
Application.DoEvents();
}
else
{
displayBoxChatArea.Text = text;
Application.DoEvents();
}
}
enterCount++;
tcpClient.Close();
}
[インターネット上で動作していないTCP/IPクライアントサーバー]の可能複製(http://stackoverflow.com/questions/7065838/tcp-ip-client-server-not-working-over-internet) – Joe