private Socket m_socketSend; //用于监听的SOCKET
private Socket m_socketWatch;
//创建监听连接的线程
private Thread AcceptSocketThread;
//初始化服务
public void InitService(string address, string port, ReceiveCallBack recvCall = null)
{
try
{
m_socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//获取ip地址
IPAddress ip = IPAddress.Parse(address.Trim());
//创建端口号
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(port.Trim()));
//绑定IP地址和端口号
m_socketWatch.Bind(point);
//开始监听:设置最大连接请求数目
m_socketWatch.Listen(10);
if (recvCall != null)
{
m_recvCallBack = recvCall;
string strMsg = "开启监听成功!";
byte[] buffer = Encoding.Default.GetBytes(strMsg);
m_recvCallBack("", buffer, buffer.Length);
}
//创建线程
AcceptSocketThread = new Thread(new ParameterizedThreadStart(StartListen));
AcceptSocketThread.IsBackground = true;
AcceptSocketThread.Start(m_socketWatch);
}
catch (SocketException ex)
{
byte[] buffer = Encoding.Default.GetBytes(ex.Message);
m_recvCallBack("", buffer, buffer.Length);
}
}
评论