private void SelectTerminalFrm_FormClosed(object sender, FormClosedEventArgs e)
{
socketIndex = 0;
localSocket.Close();
}
首先我接受服务器消息是死循环读取,发送消息也是死循环发送,应为我是每三秒钟要向服务器发送一个消息,所以采用死循环. 我的窗体关闭事件代码如上,怎么socket关闭不了呢?那位大虾解释一下,是怎么回事?
{
socketIndex = 0;
localSocket.Close();
}
首先我接受服务器消息是死循环读取,发送消息也是死循环发送,应为我是每三秒钟要向服务器发送一个消息,所以采用死循环. 我的窗体关闭事件代码如上,怎么socket关闭不了呢?那位大虾解释一下,是怎么回事?
socket.Close(); //关闭
/// 指定连接的服务器ip和端口
/// </summary>
private void ConnServer()
{
//指定好服务器端的ip地址
ipa = IPAddress.Parse(ipAddress);
//指定服务器端的ip和端口
ipendpoint = new IPEndPoint(ipa, ports);
//启动一个线程
Thread thread = new Thread(new ThreadStart(ConnSocket));
thread.Start();
} /// <summary>
/// 连接到服务器
/// </summary>
private void ConnSocket()
{
try
{
//创建一个socket连接到服务器
localSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
localSocket.Connect(ipendpoint);
//连接成功后马上启用一个线程向服务器发送消息
Thread t = new Thread(SendServerInfo);
t.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Thread thread = new Thread(new ThreadStart(Getmsg));
thread.Start();
} /// <summary>
/// 接收服务器数据
/// </summary>
private void Getmsg()
{ while (true)
{
byte[] bufData = new byte[10];
string strSbInfo = "";
if (localSocket.Connected)
{
try
{
localSocket.Receive(bufData, 2, 0);
int len0 = bufData[0] * 1;
int len1 = bufData[1] * 255;
int len = len0 + len1;
while (len > 0)
{
bufData = new byte[len];
int recIndex = localSocket.Receive(bufData, len, 0);
Console.WriteLine("recIndex:" + recIndex.ToString());
strSbInfo = strSbInfo + Encoding.Default.GetString(bufData).Trim();
len = len - recIndex;
if (len > 0)
{
strSbInfo = strSbInfo.Substring(0, (strSbInfo.Length - len));
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message + "235");
}
if (strSbInfo.Length > 0)
{
byte[] bufHeart = Encoding.Default.GetBytes(strSbInfo.ToString());
//判断主info的类型
MainDataType(Convert.ToInt32(bufHeart[0]), Convert.ToInt32(bufHeart[1]), strSbInfo);
}
}
}
}
{
try
{
//向服务器发送信息
while (localSocket.Connected)
{
if (byteQueue.Count > 0)
{
byte[] byteData = byteQueue.Dequeue();
localSocket.Send(byteData, byteData.Length, 0);
}
Thread.Sleep(100);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message + "860");
}
}