Socke服务器连接方法
1 namespace Socke服务器 2 { 3 public partial class Form1 : Form 4 { 5 Thread Watch = null;//负责监听线程 6 Socket sockeWatch = null; 7 public Form1() 8 { 9 InitializeComponent(); 10 TextBox.CheckForIllegalCrossThreadCalls = false; 11 } 12 /// <summary> 13 /// 连接服务器 14 /// </summary> 15 /// <param name="sender"></param> 16 /// <param name="e"></param> 17 private void btn_Click(object sender, EventArgs e) 18 { 19 //创建服务器端负责监听的套接字,参数是(使用IP4协议没使用流连接,使用TCP协议传输数据) 20 sockeWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 21 //获取IP地址对象 22 IPAddress adress = IPAddress.Parse(tbIP.Text.Trim()); 23 //创建包含IP和port的网络节点对象 24 IPEndPoint endpoint=new IPEndPoint (adress,int.Parse(tbport.Text.Trim())); 25 //将负责监听的套接字绑定到唯一的IP和端口上 26 sockeWatch.Bind(endpoint); 27 //设置监听队列的长度 28 sockeWatch.Listen(10); 29 Watch = new Thread(Watchsocke); 30 Watch.IsBackground = true; 31 Watch.Start(); 32 ShowMsg("客户端连接诶成功!"); 33 } 34 35 void Watchsocke() 36 { 37 Socket cokConnection = sockeWatch.Accept(); 38 ShowMsg("客户端连接诶成功!~~"); 39 } 40 void ShowMsg(string msg) 41 { 42 txtmes.AppendText(msg + "\r\n"); 43 } 44 } 45 }
下面在写一个简单的客户端连接
namespace socke客户端 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btn_Click(object sender, EventArgs e) { IPAddress adress = IPAddress.Parse(tbIP.Text.Trim()); IPEndPoint endPoint = new IPEndPoint(adress, int.Parse(tbport.Text.Trim())); Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socketClient.Connect(endPoint); } } }