日期:2014-05-18 浏览次数:21063 次
private int _port = 6868; private const int _maxPacket = 64; private TcpListener _tcpl = null; public string userip; public Hashtable _transmit_tb = new Hashtable(); static void Main(string[] args) { Listen l = new Listen(); try { l.startup(); } catch (Exception) { } } public void startup() { IPAddress _ip = Dns.GetHostAddresses(Dns.GetHostName())[0]; _tcpl = new TcpListener(_ip, _port); _tcpl.Start(); Console.WriteLine(string.Format("the server ip is {0},and the port is {1}", _ip, _port)); Console.WriteLine("server has been started,is listening..."); while (true) { byte[] packetBuff = new byte[_maxPacket]; Socket newClient = _tcpl.AcceptSocket(); IPEndPoint ip = (IPEndPoint)newClient.RemoteEndPoint; //userip = ip.Address.ToString().TrimEnd() + ":" + ip.Port; userip = ip.Address.ToString().TrimEnd(); if (_transmit_tb.Count != 0 && _transmit_tb.ContainsKey(userip)) { _transmit_tb.Remove(userip); _transmit_tb.Add(userip, newClient); } else _transmit_tb.Add(userip, newClient); string svrlog = string.Format("new ip {0} at {1} is connected,current online number is {2}", userip + ":" + ip.Port, DateTime.Now, _transmit_tb.Count); Console.WriteLine(svrlog); Thread clientthread = new Thread(new ParameterizedThreadStart(threadfun)); clientthread.Start(userip); clientthread.IsBackground = true; Thread.Sleep(200); } } private void threadfun(object obj) { Socket clientsocket = _transmit_tb[obj] as Socket; while (true) { try { if (clientsocket == null || clientsocket.Available < 1) { Thread.Sleep(300); continue; } byte[] _cmdBuff = new byte[128]; int size = clientsocket.Receive(_cmdBuff); //在这里处理收到的数据 //向客户端发送数据 clientsocket.Send(_cmdBuff); } catch (SocketException) { _transmit_tb.Remove(obj); clientsocket.Close(); Thread.CurrentThread.Abort(); } } }
// Server.cs class Server { static void Main(string[] args) { TcpListener listener = new TcpListener(IPAddress.Any, 4567); listener.Start(); while (true) { Socket socket = listener.AcceptSocket(); StateObject so = new StateObject() { socket = socket }; so.socket.BeginReceive(so