Socket(套接字)是一种独立于协议的网络编程接口,在OSI模型中,主要集中于会话层和传输层。Socket 实际上代表的是两个实体之间进行通信的有效端点。通过socket可以获得源IP地址和源端口、终点IP地址和终点端口。用户可以将多个socket连入同一个端口,以便对于单个端口可以有多个连接。通过socket客户/服务器编程可以创建一个能被许多人使用的分布式程序,并且所有客户均可以用统一的前端进行工作,并与服务器进行通信。这与老式或新式电话机之间的通话过程是十分相似的。
在.NET中,System.Net.Sockets 命名空间为需要严密控制网络访问的开发人员提供了 Windows Sockets (Winsock) 接口的托管实现。Socket 类为网络通信提供了一套丰富的方法和属性。
如果应用程序在执行期间只需要一个线程,请使用下面的方法,这些方法适用于同步操作模式。
- 如果当前使用的是面向连接的协议(如 TCP),则服务器可以使用 Listen 方法侦听连接。Accept 方法处理任何传入的连接请求,并返回可用于与远程主机进行数据通信的 Socket。可以使用此返回的 Socket 来调用 Send 或 Receive 方法。如果要指定本地 IP 地址和端口号,请在调用 Listen 方法之前先调用 Bind 方法。如果不调用 Bind,基础服务提供程序将为您分配这些值。此后,可以使用 LocalEndPoint 属性来标识分配给 Socket 的 IP 地址和端口号。如果想连接到侦听主机,请调用 Connect 方法。若要进行数据通信,请调用 Send 或 Receive 方法。
- 如果当前使用的是无连接协议(如 UDP),则根本不需要侦听连接。调用 ReceiveFrom 方法可接受任何传入的数据报。使用 SendTo 方法可将数据报发送到远程主机。

开发一个简单的同步网络聊天程序程序分为服务器和客户端。连接成功后,服务器和客户端之间可以进行对话。源码中对每一个涉及到的对初学者较难理解的类\方法\属性都有详细的注释。以下是服务器端代码。
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Net; using System.Net.Sockets; using System.Threading; using System.Text; namespace 聊天_socket { /// <summary> /// Form1 的摘要说明。 /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.StatusBar statusBar1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.RichTextBox rtbReceive; private System.Windows.Forms.RichTextBox rtbSend; private System.Windows.Forms.TextBox txtServer; private System.Windows.Forms.TextBox txtPort; private System.Windows.Forms.Button btnListen; private System.Windows.Forms.Button btnSend; private System.Windows.Forms.Button btnStop; private IPAddress hostIPAddress=IPAddress.Parse("127.0.0.1"); private IPEndPoint Server; private Socket listeningSocket; private Socket mySocket; string port; /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.Container components = null;
public Form1() { // // Windows 窗体设计器支持所必需的 // InitializeComponent();
// // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // }
/// <summary> /// 清理所有正在使用的资源。 /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); }
#region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.rtbReceive = new System.Windows.Forms.RichTextBox(); this.rtbSend = new System.Windows.Forms.RichTextBox(); this.txtServer = new System.Windows.Forms.TextBox(); this.txtPort = new System.Windows.Forms.TextBox(); this.statusBar1 = new System.Windows.Forms.StatusBar(); this.btnListen = new System.Windows.Forms.Button(); this.btnSend = new System.Windows.Forms.Button(); this.btnStop = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // rtbReceive // this.rtbReceive.Location = new System.Drawing.Point(80, 56); this.rtbReceive.Name = "rtbReceive"; this.rtbReceive.Size = new System.Drawing.Size(264, 96); this.rtbReceive.TabIndex = 0; this.rtbReceive.Text = ""; // // rtbSend // this.rtbSend.Location = new System.Drawing.Point(80, 152); this.rtbSend.Name = "rtbSend"; this.rtbSend.Size = new System.Drawing.Size(264, 96); this.rtbSend.TabIndex = 1; this.rtbSend.Text = ""; // // txtServer // this.txtServer.Location = new System.Drawing.Point(72, 16); this.txtServer.Name = "txtServer"; this.txtServer.TabIndex = 2; this.txtServer.Text = "127.0.0.1"; // // txtPort // this.txtPort.Location = new System.Drawing.Point(288, 16); this.txtPort.Name = "txtPort"; this.txtPort.Size = new System.Drawing.Size(48, 21); this.txtPort.TabIndex = 3; this.txtPort.Text = "19811"; // // statusBar1 // this.statusBar1.Location = new System.Drawing.Point(0, 287); this.statusBar1.Name = "statusBar1"; this.statusBar1.ShowPanels = true; this.statusBar1.Size = new System.Drawing.Size(360, 22); this.statusBar1.TabIndex = 4; this.statusBar1.Text = "statusBar1"; // // btnListen // this.btnListen.Location = new System.Drawing.Point(32, 256); this.btnListen.Name = "btnListen"; this.btnListen.TabIndex = 5; this.btnListen.Text = "开始监听"; this.btnListen.Click += new System.EventHandler(this.btnListen_Click); // // btnSend // this.btnSend.Location = new System.Drawing.Point(144, 256); this.btnSend.Name = "btnSend"; this.btnSend.TabIndex = 6; this.btnSend.Text = "发送信息"; this.btnSend.Click += new System.EventHandler(this.btnSend_Click); // // btnStop // this.btnStop.Location = new System.Drawing.Point(256, 256); this.btnStop.Name = "btnStop"; this.btnStop.TabIndex = 7; this.btnStop.Text = "停止监听"; this.btnStop.Click += new System.EventHandler(this.btnStop_Click); // // label1 // this.label1.Location = new System.Drawing.Point(16, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(56, 23); this.label1.TabIndex = 8; this.label1.Text = "服务器:"; // // label2 // this.label2.Location = new System.Drawing.Point(216, 16); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(64, 23); this.label2.TabIndex = 9; this.label2.Text = "监听端口:"; // // label3 // this.label3.Location = new System.Drawing.Point(16, 64); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(64, 23); this.label3.TabIndex = 10; this.label3.Text = "接收信息:"; // // label4 // this.label4.Location = new System.Drawing.Point(16, 152); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(64, 23); this.label4.TabIndex = 11; this.label4.Text = "发送信息:"; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(360, 309); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.btnStop); this.Controls.Add(this.btnSend); this.Controls.Add(this.btnListen); this.Controls.Add(this.statusBar1); this.Controls.Add(this.txtPort); this.Controls.Add(this.txtServer); this.Controls.Add(this.rtbSend); this.Controls.Add(this.rtbReceive); this.Name = "Form1"; this.Text = "聊天程序-服务器"; this.TopMost = true; this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing); this.ResumeLayout(false);
} #endregion
/// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); }
private void btnListen_Click(object sender, System.EventArgs e) { try { hostIPAddress=IPAddress.Parse(txtServer.Text); port=txtPort.Text; } catch{MessageBox.Show("请输入正确的IP地址格式");} try { //通过组合服务的主机 IP 地址和端口号,IPEndPoint 类形成到服务的连接点。 Server=new IPEndPoint(hostIPAddress,Int32.Parse(port)); // Create a socket object to establish a connection with the server listeningSocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); listeningSocket.Bind(Server); //绑定该主机端口 listeningSocket.Listen(50); //监听端口,等待客户端连接请求。50是队列中最多可容纳的等待接受的传入连接数 statusBar1.Text="主机"+txtServer.Text+"端口"+txtPort.Text+"开始监听....."; //Accept 以同步方式从侦听套接字的连接请求队列中提取第一个挂起的连接请求,然后创建并返回新的 Socket。 mySocket=listeningSocket.Accept(); //一个进程可以创建一个或多个线程以执行与该进程关联的部分程序代码。使用 ThreadStart 委托指定由线程执行的程序代码。 Thread thread=new Thread(new ThreadStart(ThreadProc)); thread.Start(); } catch(Exception ee){statusBar1.Text=ee.Message;} } private void ThreadProc() { if(mySocket.Connected) { statusBar1.Text="与客户建立连接."; while(true) { Byte[] ByteRecv=new Byte[256]; mySocket.Receive(ByteRecv,ByteRecv.Length,0); string strRecv=Encoding.BigEndianUnicode.GetString(ByteRecv); rtbReceive.AppendText(strRecv+"\r\n"); } } }
private void btnStop_Click(object sender, System.EventArgs e) { try { listeningSocket.Close(); statusBar1.Text="主机"+txtServer.Text+"端口"+txtPort.Text+"监听停止"; } catch{MessageBox.Show("监听尚未开始,关闭无效");} }
private void btnSend_Click(object sender, System.EventArgs e) { try { string strSend ="Server--->"+rtbSend.Text+"\r\n"; Byte[] ByteSend = Encoding.BigEndianUnicode.GetBytes(strSend); mySocket.Send(ByteSend,ByteSend.Length,0); } catch{MessageBox.Show("连接尚未建立,无法发送.");} }
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { try { listeningSocket.Close();//在窗口关闭之前关闭Scoket连接并释放所有关联的资源。 } catch{} } } }

|