
Socket socketClints = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //侦听socket
//socketClints.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
socketClints.Bind(new IPEndPoint(IPAddress.Any, portSocketInt)); socketClints.Listen();
socketClints.BeginAccept(new AsyncCallback(ClientAccepted), socketClints); //开始接收来自浏览器的http请求(其实是socket连接请求)
#region 客户端连接成功 byte[] buffer = new byte[];
/// <summary>
/// 客户端连接成功
/// </summary>
/// <param name="ar"></param>
public void ClientAccepted(IAsyncResult ar)
{
#region
var socket = ar.AsyncState as Socket;
//这就是客户端的Socket实例,我们后续可以将其保存起来
var client = socket.EndAccept(ar); //接收客户端的消息(这个和在客户端实现的方式是一样的)异步
client.BeginReceive(buffer, , buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), client);
//准备接受下一个客户端请求(异步)
socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
#endregion
}
#endregion #region 接收客户端的信息
/// <summary>
/// 接收某一个客户端的消息
/// </summary>
/// <param name="ar"></param>
public void ReceiveMessage(IAsyncResult ar)
{
int length = ; var socket = ar.AsyncState as Socket;
//客户端IP地址和端口信息
try
{
#region
//方法参考:http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.endreceive.aspx
length = socket.EndReceive(ar); //读取出来消息内容
string recv_request = Encoding.UTF8.GetString(buffer, , length);
//输出接收信息
//WriteLine(clientipe + " :" + message, ConsoleColor.White);
//消息处理
socketResolve(recv_request, socket);
//服务器发送消息
//socket.Send(Encoding.UTF8.GetBytes("server received data")); //默认Unicode
//接收下一个消息(因为这是一个递归的调用,所以这样就可以一直接收消息)异步
socket.BeginReceive(buffer, , buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
#endregion
}
catch
{
//设置计数器 }
}
//发送方法 需要修改数据
public void sendData()
{ byte[] data=System.Text.Encoding.UTF8.GetBytes(Encrypt(txt,sKey));
byte[] byLen = BitConverter.GetBytes(data.Length);
socket.Send(byLen);
//socket.Send();
socket.Send(data);
}
#endregion
客户端:
ThStartBool=true;
newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
while (ThStartBool)
{
try
{
newSocket.Connect(ip, int.Parse(port)); socketSend("url/" + obj.ToString() + "_OK/");
Invoke(updateLableText, "连接成功"); //ReceiveObject state = new ReceiveObject() { Client = newSocket };
//newSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), state);
newSocket.BeginReceive(m_byLen, 0, m_byLen.Length, SocketFlags.None, new AsyncCallback(RecvLen), newSocket); ThStartBool = false;
}
catch (Exception)
{ Thread.Sleep();//3秒后重新连接
}
}
int m_nIndex = 0, m_nRecvLen = 0;
byte[] m_byLen = new byte[4];
byte[] m_byData = null; private void RecvLen(IAsyncResult ar)
{
try
{
Socket sock = ar.AsyncState as Socket;
int nLen = sock.EndReceive(ar); m_nRecvLen += nLen;
if (m_nRecvLen != m_byLen.Length)
{
m_nIndex += nLen;
sock.BeginReceive(m_byLen, m_nIndex, m_byLen.Length - m_nIndex, SocketFlags.None, new AsyncCallback(RecvLen), sock);
}
else
{
m_nIndex = m_nRecvLen = 0;
m_byData = new byte[BitConverter.ToUInt32(m_byLen, 0)];
sock.BeginReceive(m_byData, m_nIndex, m_byData.Length - m_nIndex, SocketFlags.None, new AsyncCallback(RecvData), sock); }
} catch (Exception ex)
{
Invoke(updateLableText, "与服务器失去联系,正在尝试重连");
ThStartBool = true;
th = new Thread(new ParameterizedThreadStart(ThStartData));
th.Start(signID);
}
} private void RecvData(IAsyncResult ar)
{
Socket sock = ar.AsyncState as Socket;
int nLen = sock.EndReceive(ar);
m_nRecvLen += nLen;
if (m_nRecvLen != m_byData.Length)
{
m_nIndex += nLen;
sock.BeginReceive(m_byData, m_nIndex, m_byData.Length - m_nIndex, SocketFlags.None, new AsyncCallback(RecvData), sock);
}
else
{
m_nIndex = m_nRecvLen = 0;
//MessageBox.Show(Encoding.UTF8.GetString(m_byData));
string sKey = signID.Substring(2, 3) + signID.Substring(5, 3) + signID.Substring(10, 2);
//读取出来消息内容
var message = Encoding.UTF8.GetString(m_byData);
dataParsing(Decrypt(message.ToString(), sKey));
sock.BeginReceive(m_byLen, m_nIndex, m_byLen.Length - m_nIndex, SocketFlags.None, new AsyncCallback(RecvLen), sock);
}
}