我有一个TcpClient应用程序,它从客户端向服务器发送消息。 代码如下:
clsServer.cs
public void server_start()
{
this.tcpListener = new TcpListener(new IPAddress(new Byte[] { 172, 16, 1, 55 }), 9999);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
_rtb_Input.AppendText("Listening... Press any key to stop" + System.Environment.NewLine);
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
public event MessageReceivedHandler MessageReceived;
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = clientStream.Read(message, 0, 4096);
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
string msg = encoder.GetString(message, 0, bytesRead);
if (this.MessageReceived != null)
{
this.MessageReceived(msg);
}
//send message back select the message from the db
byte[] buffer = encoder.GetBytes("Hello Client!");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
tcpClient.Close();
}
frmClient.cs
public frmClient()
{
InitializeComponent();
}
private void btn_ClientStart_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("172.16.1.55"), 9999);
try
{
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(rtb_Outpot.Text);
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
catch (Exception ex)
{
rtb_Outpot.AppendText(System.Environment.NewLine + "Failed To Connect to the Server" + System.Environment.NewLine);
}
}
frmServer.cs
private void btn_ServerStart_Click(object sender, EventArgs e)
{
btn_ServerStop.Enabled = true;
btn_ServerStart.Enabled = false;
server = new clsServer(rtb_Input);
server.MessageReceived += new MessageReceivedHandler(Message_Received);
server.server_start();
}
private void Message_Received(string message)
{
//update the display using invoke
Invoke(new MessageReceivedHandler(PrintToScreen), new object[] { message });
}
private void PrintToScreen(string msg)
{
msg_counter++;
rtb_Input.AppendText("msg no': " + msg_counter + System.Environment.NewLine + msg + System.Environment.NewLine);
}
当我从客户端向服务器发送消息时,工作正常。 但现在我可以找到一种方法将数据从服务器发送回客户端。 我是否还必须为客户表单创建一个帖子?
感谢。
答案 0 :(得分:1)
发布的代码看起来更像是在试图找到接收从服务器发送的消息的方法。 clsServer.cs中的代码已包含将数据发送到客户端所需的代码。
您的客户端代码缺少必要的调用来读取clientStream
的响应。在您的应用程序中实现的方式将根据您的要求而有所不同。就个人而言,我可能会将阅读内容卸载到另一个帖子中。