日期:2014-05-17 浏览次数:21565 次
public void OnConnectRequest(IAsyncResult ar) { try { //初始化一个SOCKET,用于其它客户端的连接 server1 = (Socket)ar.AsyncState; Client = server1.EndAccept(ar); //将要发送给连接上来的客户端的提示字符串e DateTimeOffset now = DateTimeOffset.Now; Byte[] byteDateLine = new byte[1048576]; remote = Client.RemoteEndPoint; //连接成功 写入到日志文件中 Log.wlog(Client.RemoteEndPoint.ToString() + "连接成功。" + now.ToString("G") + "\r\n"); userListOperate(Client.RemoteEndPoint.ToString()); //等待新的客户端连接 server1.BeginAccept(new AsyncCallback(OnConnectRequest), server1); while (true) { int recv = Client.Receive(byteDateLine); string stringdata = Encoding.UTF8.GetString(byteDateLine, 0, recv); string ip = Client.RemoteEndPoint.ToString(); //获取客户端的IP和端口 if (recv <= 0) { //当客户端终止连接时 Log.wlog(ip + " " + now.ToString("G") + " " + "已从服务器断开" + "\r\n"); //在这里做处理 连接端口 释放端口 并删除userList的显示 if (userList.InvokeRequired) { MyInvoke _myinvoke = new MyInvoke(userListOperateR); userList.Invoke(_myinvoke, new object[] { ip }); } else { userList.Items.Remove(ip); } Client.Close(); break; } ......转发消息的程序 } catch (Exception e) { Log.wlog("异常信息或者连接断开\r\n" + e.Message + "\r\n"); Client.Close(); } }