日期:2014-05-18 浏览次数:20828 次
TcpListener dataListener = null; Socket dataSocket = null; private void FormMain_Load(object sender, EventArgs e) { BeginListen(); tmr.Enabled = true; } private void BeginListen() { string IP = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(); IPEndPoint dataEndPoint = new IPEndPoint(IPAddress.Parse(IP), 6005); dataListener = new TcpListener(dataEndPoint); dataListener.Start(); } private void timer1_Tick(object sender, EventArgs e) { DataListen(); } private void DataListen() { if (dataListener.Pending()) { dataSocket = dataListener.AcceptSocket(); //Thread ShowMsgThread = new Thread(new ThreadStart(ShowMsg)); //ShowMsgThread.Start(); } } private void ShowMsg() { byte[] buffer = new byte[1024 * 1024 * 5]; try { while (true) { dataSocket.Receive(buffer); string bufferLine = Encoding.Default.GetString(buffer, 0, buffer.Length); string[] bufferTine = bufferLine.Split(new string[] { "|" }, StringSplitOptions.None); if (bufferTine[0] == txbIP.Text) { if (bufferTine[1] == Dns.GetHostAddresses(Dns.GetHostName())[0].ToString()) { if (bufferTine[2] == "connect") { } } } } } catch (Exception) { //异常 } } private void SendMsg(string Msg) { string ServerIP = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(); string ClientIP = txbIP.Text; byte[] SendMsg = Encoding.Default.GetBytes(ServerIP + "|" + ClientIP + "|" + Msg); dataSocket.Send(SendMsg); }
private void DataListen() { if (dataListener.Pending()) { dataSocket = dataListener.AcceptSocket(); } }