我正在寻找一种在 TCP 中实现协议以发送和接收简单字符串消息的方法。我有一个客户端和一个服务器应用程序,当它们第一次开始运行时,我按下客户端上的连接按钮以连接到服务器。服务器的列表框上会弹出一些文本,说明客户端已连接,客户端的列表框上会出现一些文本,说明它已连接到服务器。
那部分工作正常,但现在我希望能够将其他字符串发送到服务器,并且根据我发送的字符串会使服务器执行某个操作,我该怎么做?想到的第一个想法是在某处使用 if-then 语句。我将在下面发布我的代码:
服务器:
private static int port = 8080;
private static TcpListener listener;
private static Thread thread;
private void Form1_Load(object sender, EventArgs e)
{
listener = new TcpListener(new IPAddress(new byte[] { 10, 1, 6, 130 }), port);
thread = new Thread(new ThreadStart(Listen));
thread.Start();
}
private void Listen()
{
listener.Start();
listBox1.Invoke(new EventHandler(delegate { listBox1.Items.Add("Listening on: " + port.ToString()); }));
while (true)
{
listBox1.Invoke(new EventHandler(delegate { listBox1.Items.Add("Waiting for connection...."); }));
TcpClient client = listener.AcceptTcpClient();
Thread listenThread = new Thread(new ParameterizedThreadStart(ListenThread));
listenThread.Start(client);
}
}
//client thread
private void ListenThread(Object client)
{
NetworkStream netstream = ((TcpClient)client).GetStream();
listBox1.Invoke(new EventHandler(delegate { listBox1.Items.Add("Request made"); }));
byte[] resMessage = Encoding.ASCII.GetBytes("Connected to Server");
netstream.Write(resMessage, 0, resMessage.Length);
netstream.Flush();
}
客户:
TcpClient tcpclnt;
private void buttonConnect_Click(object sender, EventArgs e)
{
try
{
tcpclnt = new TcpClient();
userEventBox.Items.Add("Connecting.....");
try
{
tcpclnt.Connect("10.1.6.130", 8080);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
Stream stm = tcpclnt.GetStream();
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
string returndata = System.Text.Encoding.ASCII.GetString(bb);
userEventBox.Items.Add(returndata);
tabControl1.Enabled = true;
//need a way for the server see this string
string populateList = "Test";
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(populateList);
stm.Write(ba, 0, ba.Length);
}
catch (Exception ex)
{
Console.WriteLine("Error..... " + ex.StackTrace);
}
}
我很困惑,希望您能在这个问题上提供任何帮助。谢谢你。
来源-> C# 客户端-服务器协议/模型问题