如果我还有这样的接收消息的代码呢? var proxSocket=socket as Socket; byte[]data=new byte[1024*1024]; while (true) { int len = 0; try { len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None); } catch { AppendTextToTxtLog(string.Format("服务器端:{0}非正常退出",proxSocket.RemoteEndPoint.ToString())); StopConnect(); return; } if (len <= 0) { AppendTextToTxtLog(string.Format("服务器端:{0}正常退出", proxSocket.RemoteEndPoint.ToString())); StopConnect(); return; } int type = data[0]; if (type == 1) { string str=Encoding.Default.GetString(data,1,len-1); AppendTextToTxtLog(string.Format("接收到服务器端:{0}的消息是:{1}", proxSocket.RemoteEndPoint.ToString(), str)); }else if(type == 2) { Flash(); }else if (type == 3) { saveFile(data, len); } }
时间: 2024-02-10 12:08:14 浏览: 166
在关闭连接时,您需要停止接收数据并退出循环。可以添加一个布尔变量 `isConnected`,并在关闭连接时将其设置为 `false`。然后在循环中,检查此变量的值,如果为 `false`,则退出循环。以下是修改后的代码示例:
```
var proxSocket = socket as Socket;
byte[] data = new byte[1024 * 1024];
bool isConnected = true; // 添加 isConnected 变量
while (isConnected) // 修改循环条件
{
int len = 0;
try
{
len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None);
}
catch
{
AppendTextToTxtLog(string.Format("服务器端:{0}非正常退出", proxSocket.RemoteEndPoint.ToString()));
StopConnect();
return;
}
if (len <= 0)
{
AppendTextToTxtLog(string.Format("服务器端:{0}正常退出", proxSocket.RemoteEndPoint.ToString()));
StopConnect();
return;
}
int type = data[0];
if (type == 1)
{
string str = Encoding.Default.GetString(data, 1, len - 1);
AppendTextToTxtLog(string.Format("接收到服务器端:{0}的消息是:{1}", proxSocket.RemoteEndPoint.ToString(), str));
}
else if (type == 2)
{
Flash();
}
else if (type == 3)
{
saveFile(data, len);
}
}
```
在关闭连接时,将 `isConnected` 设置为 `false`:
```
isConnected = false;
ClientSocket.Shutdown(SocketShutdown.Both);
ClientSocket.Close();
```
阅读全文