本帖最后由 淡.。 于 2013-4-20 12:27 编辑
- Thread thread,thread2;
- Socket socket2;
- thread = new Thread(accept);//创建一个线程
- thread.IsBackground = true;//设置为后台线程
- thread.Start();//开始执行线程
- textBox3.AppendText ( "服务器开始监听\n");
- thread2 = new Thread(jieshou);
- thread2.IsBackground = true;
- thread2.Start();
- void accept()
- {
- while (true)
- {
-
- socket2 = socketfrist.Accept();//开始监听客户端请求
- ss.Add(socket2 .RemoteEndPoint .ToString (),socket2 );//监听到请求之后 ,把刚创建的套接字存在字典集合里
-
- listBox1.Items.Add(socket2.RemoteEndPoint.ToString());//再插入lisbox框中
- string endpoint =socket2.RemoteEndPoint.ToString ();//获取客户端的ip和端口 也就是终结点
- show("客户端连接成功"+endpoint );
-
- }
- void jieshou()
- {
- while (true)
- {
-
- byte[] mee = new byte[1024 * 1024];
- int length= socket2.Receive(mee);
- string mgg = System.Text.Encoding.UTF8.GetString(mee,0,length);
- textBox3.AppendText(mgg + "\n");
- }
- }
复制代码 系统提示在jieshou方法中socket2说我没有实例化,我在accept()方法中 socket2 = socketfrist.Accept();//已经实例化了 是因为不同线程的原因导致另外一个线程不能访问已实例化的socket2吗,有什么办法能让别的线程访问到该线程的实例化对象呢? |