namespace test3{using System;
using System .Net .Sockets ;
using System .Net ;
using System .Text ;
using System .Threading ;
using System.Collections;
using System .IO ;
using UnityEngine;  public class Socketfz
{
public static Socket soc =null ;
private static Thread nthread = null;
private static Thread thread = null;
private static byte[] buffer = new byte[1024];
public static string data ;
public static string data2;
public static string data3 ;
public static string data4 ;
public static string data5 ;
public Socketfz ()
{
} public void SocketConnection(string Lip ,int Lport){

IPAddress ip = IPAddress.Parse (Lip);
soc = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint (ip, Lport);

soc.Bind (ipep);
soc.Listen (10);
thread = new Thread (new ThreadStart (ListenC));
thread .Start ();
}
static void ListenC(){

while(true){
try{
Socket s = soc.Accept();
s.Send(Encoding.ASCII.GetBytes("success!"));
nthread = new Thread(Redata);
nthread.Start(s);

}catch(Exception e ){
MonoBehaviour .print (e.ToString());

}
}
}

static void Redata(object socket){
Socket socket1 = (Socket)socket; while (true) {

try{

int rs = socket1.Receive (buffer,buffer.Length ,0);
if(rs == 0){
continue ;
}
data = Encoding .ASCII .GetString (buffer,0,rs);
}catch (Exception e){
MonoBehaviour .print (e.ToString());
socket1 .Shutdown(SocketShutdown.Both);
socket1 .Close();
break;
}
}
}


}
}
当再有一个电脑接入的时候,我想再添加一个线程来处理它发送的数据。应该怎么添加啊????

解决方案 »

  1.   

    你可以直接使用BeginAccept方法来创建一个线程池线程来处理发送数据,你的代码都是使用的是同步代码而且需要自己手动创建线程,使用BeginAccept方法,该方法内部自动使用线程池线程来处理,当另一台电脑连接的连接的时候,该方法会自动使用线程池线程对其处理,而不需要你再手动创建线程,具体方法的使用如下:
    http://msdn.microsoft.com/zh-cn/library/vstudio/system.net.sockets.socket.beginaccept.aspx
      

  2.   

    如果后期处理是一个同步的while(true),那么BeginAccept不是一个好的习惯,它会对IO线程池产生一些影响,最好是创建一个自己的工作线程池。