c# socket
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; } } }
•------------------相关类--------------------------
•IPAddress类:包含了一个IP地址
•IPEndPoint类:包含了一对IP地址和端口号
•--------------------方法们------------------------------
•Socket (): 创建一个Socket
•Bind(): 绑定一个本地的IP和端口号(IPEndPoint)
•Listen(): 让Socket侦听传入的连接尝试,并指定侦听队列容量
•Connect(): 初始化与另一个Socket的连接
•Accept(): 接收连接并返回一个新的socket
•Send(): 输出数据到Socket
•Receive(): 从Socket中读取数据
•Close(): 关闭Socket (销毁连接)