我創建了一個相互連接的客戶端和服務器。服務器能夠發送客戶端發送回客戶端的消息(處理後)...但是...如果有兩個客戶端連接,它只會將消息發送回發送消息的客戶端(大聲笑...)客戶端服務器通信故障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();
}
可能重複(http://stackoverflow.com/questions/7065838/tcp-ip-client-server-not-working-over-internet) – Joe