问题描述
我的C#技能仍然相当基础,但是通过反复试验,我设法创建了一个Windows Forms服务器,该服务器允许多个连接以及一个客户端来发送消息并获取响应。 但是,从遥远的VB经验中我知道,请求可能并不总是与答案1:1匹配,因为连接可能不稳定。 我当前的代码“有效”,但可能不好。客户端无法处理来自服务器的零碎答案,如果没有收到答案,它将挂起。
是否可以证明我的代码考虑到这一点?抱歉,如果我把所有东西都用完了,请感谢有人能忍受我!
服务器代码:
public List<TcpClient> tcpClient = new List<TcpClient>();
public async void ListenForConnection(int index)
{
TcpListener listener = new TcpListener(System.Net.IPAddress.Any,5036);
listener.Start();
while(true)
try
{
tcpClient.Add(await listener.AcceptTcpClientAsync());
WaitForMessage(tcpClient.Count - 1);
}
catch
{
}
}
public async void WaitForMessage(int index)
{
NetworkStream stream = tcpClient[index].GetStream();
StreamWriter sw = new StreamWriter(tcpClient[index].GetStream());
while (true)
{
try
{
byte[] buffer = new byte[1024];
await stream.ReadAsync(buffer,buffer.Length);
int recv = 0;
foreach (byte b in buffer)
{
if (b != 0)
{
recv++;
}
}
string request = Encoding.UTF8.GetString(buffer,recv);
string response = "You said: " + request;
sw.WriteLine(response);
sw.Flush();
}
catch (Exception e)
{
if (!tcpClient[index].Connected)
{ return; }
}
}
}
客户代码:
public TcpClient tcpclient;
public async void ConnectToServer()
{
bool connected = false;
while(!connected)
try
{
tcpclient = new TcpClient();
await tcpclient.ConnectAsync(IPADDRESS,5036);
connected = true;
}
catch
{
}
}
public string ServerData(string request)
{
if (!tcpclient.Connected)
return "";
int byteCount = Encoding.UTF8.GetByteCount(request + 1);
byte[] sendData = Encoding.UTF8.GetBytes(request);
NetworkStream networkstream = tcpclient.GetStream();
networkstream.Write(sendData,sendData.Length);
StreamReader sr = new StreamReader(networkstream);
string response = sr.ReadLine();
return response;
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)