标签:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net.Sockets; using System.Net; using System.Threading; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Socket s; Thread myThread; private static byte[] result = new byte[1024]; private void button1_Click(object sender, EventArgs e) { string id = this.textBox1.Text; int post = int.Parse(this.textBox2.Text); IPAddress Ips = IPAddress.Parse(id); //服务器Ip地址 s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //建立连接 s.Bind(new IPEndPoint(Ips,post)); //绑定端口 s.Listen(10); //设置最大连接请求 myThread = new Thread(listen); //myThread.Start(s.RemoteEndPoint.ToString() + "连接成功"); myThread.IsBackground = true; myThread.Start(); } public void show(string msg) { textBox3.AppendText(msg + "\r\n"); } public void listen() { while (true) { Socket ceshi = s.Accept(); //接收连接并返回一个新的socket show(ceshi.RemoteEndPoint.ToString() + "连接成功"); ceshi.Send(Encoding.Default.GetBytes("吕志林是二货")); Thread aax = new Thread(jiaoliu); aax.Start(ceshi); } } public void jiaoliu(object o) { Socket aa = o as Socket; while (true) { try { int receiveNumber = aa.Receive(result); //从Socket中读取数据 textBox4.AppendText(aa.RemoteEndPoint.ToString() + Encoding.ASCII.GetString(result, 0, receiveNumber) + "\r\n"); } catch (Exception ex) { aa.Shutdown(SocketShutdown.Both); aa.Close(); break; } } } private void Form1_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; } } }
标签:
原文地址:http://www.cnblogs.com/mengluo/p/5639934.html