C#中用socket多线程处理服务器与客户端中出现异常

来源:百度知道 编辑:UC知道 时间:2024/05/09 02:09:07
程序启动时,直接建立多线程
public void Form1_Load(object sender, EventArgs e)
{
Thread mythread = new Thread(new ThreadStart(BeginListen));
mythread.Start();
}
BeginListen为我写的服务器端监听方法,里面有一个接受客户端消息的循环
while (true)
{
bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
richTextBox2.BeginInvoke(new dell(chang2));
sb = "11222";
msg = Encoding.ASCII.GetBytes(sb);
handler.Send(msg);
}
接受一次消息后,socket不关闭,继续等待客户端发送来消息。
连接都能正常连上,第一次好使,执行第二次循环时,直接跳到main()里的application.run()去了,爆出异常!
在 System.Reflection.TargetInvocationException 中第一次偶然出现的“mscorlib.dll”类型的异常
未处理的“System.Reflection.TargetInvocationException”类型的异常出现在 mscorlib.dll 中。
我又新建个小测试服务器,结果好使,可是拷到以前的大程序里就不行,出现
在 System.NullReferenceException 中第一次偶然

我以前写过类似的socket通信,虽然你用的方法和我的不太一样,但我还是感觉有一些问题
接受消息的时候,你用的是while(true)循环,当第一次将消息接受后,缓冲区就为空了,我想你再用循环去接收应该会出问题。
我记得有个poll方法,具体什么用途忘记了(很久没写代码了)你在循环里面加个if (clientsocket.Poll(1000, SelectMode.SelectRead))判断语句“clientsocket为你需要接收消息的socket”看看能不能解决,或者就用异步也可以,我可以发一下我以前的代码你参考下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace test4_2
{
public partial class Form1 : Form
{
Socket connectSocket;
//Socket client;
byte[] bytes = new byte[1024];
delegate void listboxDel(string s);
listboxDel listboxdel;
public Form1()
{
InitializeComponent();
textBoxContent.Focus();
listboxd