110,963
社区成员
发帖
与我相关
我的任务
分享
//接收数据
public void OnRecievedData(IAsyncResult ar) {
Socket listener = ar.AsyncState as Socket;
try {
int nBytesRec = listener.EndReceive(ar);
if (nBytesRec > 0) {
//byte ==> string
string sRecieved = Encoding.Unicode.GetString(msgBuff, 0, nBytesRec);
//处理来自客户端的消息
ProcessMessage(listener, sRecieved);
//注册消息回调函数
SetupRecieveCallback(listener);
//listener.Send(Encoding.Unicode.GetBytes(string.Format("Begin|kkun|kkun|{0}", user_list.Count <= 1)));
} else {
this.Invoke(new Action<IPEndPoint>(Tstring_User_Remove), listener.RemoteEndPoint);
this.Invoke(new Action<string>(Tstring_Info), string.Format("disconnect from server {0}", listener.RemoteEndPoint));
listener.Shutdown(SocketShutdown.Both);
listener.Close();
//continue;
}
} catch(Exception exp) {
this.Invoke(new Action<IPEndPoint>(Tstring_User_Remove), listener.RemoteEndPoint);
this.Invoke(new Action<string>(Tstring_Info), string.Format("disconnect from server {0}", listener.RemoteEndPoint));
this.Invoke(new Action<string>(Tstring_Info), string.Format("disconnect from server {0}", exp.Message));
listener.Shutdown(SocketShutdown.Both);
listener.Close();
}
}
//连接上服务器后,准备接收消息
public void OnConnect(IAsyncResult ar) {
Socket sock = (Socket)ar.AsyncState;
try {
if (sock.Connected) {
string _Command = string.Format("Login|{0}|{1}|{2}", clientInfo.UserName, clientInfo.UserName, clientInfo.UserName);
byte[] _bCommand = Encoding.Unicode.GetBytes(_Command);
client.Send(_bCommand);
AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
sock.BeginReceive(msgBuff, 0, msgBuff.Length, SocketFlags.None, recieveData, sock);
}
} catch (Exception ex) {
throw ex;
}
}
//开始侦听
public void OnConnectRequest(IAsyncResult ar) {
Socket listener = ar.AsyncState as Socket;
client = listener.EndAccept(ar);
client.BeginReceive(msgBuff, 0, msgBuff.Length, SocketFlags.None, new AsyncCallback(OnRecievedData), client);
listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
}
private void BeginService_Click(object sender, EventArgs e) {
try {
this.btnBegin.Enabled = false;
Socket listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listen.Bind(server_ip);
listen.Listen(LISTEN_NUM);
listen.BeginAccept(new AsyncCallback(OnConnectRequest), listen);
} catch (Exception) {
return;
}
}
Socket client;
private void 连接服务器ToolStripMenuItem_Click(object sender, EventArgs e) {
try {
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Blocking = false;
client.BeginConnect(clientInfo.ServerIPEndPoint, new AsyncCallback(OnConnect), client);
} catch (Exception exp) {
throw exp;
}
}
FileStream fs = new FileStream("c:\\1.xls", FileMode.Open);
if (fs != null) {
byte[] _buffer=new byte[int.MaxValue];
int i = fs.Read(_buffer, 0, (int)fs.Length);
}