日日新
苟日新
导航
博客园
首页
新随笔
联系
订阅
管理
<
2004年12月
>
日
一
二
三
四
五
六
28
29
30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
1
2
3
4
5
6
7
8
统计
随笔 - 288
文章 - 0
评论 - 609
引用 - 10
与我联系
发短消息
搜索
常用链接
我的随笔
我的空间
我的短信
我的评论
更多链接
我的参与
我的新闻
最新评论
我的标签
留言簿
(98)
给我留言
查看留言
随笔分类
CE 开发
(rss)
随笔档案
2006年3月 (3)
2006年2月 (2)
2006年1月 (6)
2005年12月 (29)
2005年11月 (48)
2005年10月 (20)
2005年9月 (31)
2005年4月 (1)
2004年12月 (29)
2004年11月 (119)
相册
全身照
程序员脚印
程序员脚印
(rss)
程序员宝库
最新评论
1. re: 图像处理
对回帖实在无语
--timedcy
2. re: 图像处理
楼主,您好! 我现在正在做图像处理软件设计方面的毕业论文,您有没有关于C++Builder数字图象处理软件设计方面的资料啊,如果有希望能发给我参考一下,我的邮箱是yulinggongwu69@...
--与灵
3. re: C/C++中的日期和时间 time_t与struct tm转换
很受教,谢了,呵呵
--小张123
4. 计算机视觉测量
尊敬的楼主:您好! 我是一名在校学生,最近要写一篇关于“基于计算机视觉测量的道路交通事故处理”方面的论文,需要编制用来测量道路事故现场的程序,牵扯图象坐标提取等等。由于图像处理方面的知识薄弱,对我...
--肖若易
5. re: Visual C++ 数据库开发-初级篇
谢谢
--刘平
阅读排行榜
1. 图像处理(87526)
2. (转载)做个性感男人的开始之做个健康品位男人,为了自己,男人就是保护女人的,要不然要男人有什么用!?(35682)
3. Visual C++界面编程 (15948)
4. (摘抄)VC技术内幕笔记(13939)
5. DES算法的介绍和实现(8378)
评论排行榜
1. 图像处理(401)
2. 好的学习网站登记(37)
3. 段掌(27)
4. Visual C++界面编程 (14)
5. (摘抄)VC技术内幕笔记(12)
实例解析SOCKET编程模型
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{}
}
}
}
以下是同步聊天程序的客户端源代码。其中的一些过程可以参考服务器端源码
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_client
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnStop;
private System.Windows.Forms.Button btnSend;
private System.Windows.Forms.TextBox txtPort;
private System.Windows.Forms.TextBox txtServer;
private System.Windows.Forms.RichTextBox rtbSend;
private System.Windows.Forms.RichTextBox rtbReceive;
private System.Windows.Forms.StatusBar statusBar1;
private System.Windows.Forms.Button btnConnect;
private IPAddress hostIPAddress;
private IPEndPoint Server;
private Socket sock;
/// <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.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.btnStop = new System.Windows.Forms.Button();
this.btnSend = new System.Windows.Forms.Button();
this.btnConnect = new System.Windows.Forms.Button();
this.txtPort = new System.Windows.Forms.TextBox();
this.txtServer = new System.Windows.Forms.TextBox();
this.rtbSend = new System.Windows.Forms.RichTextBox();
this.rtbReceive = new System.Windows.Forms.RichTextBox();
this.statusBar1 = new System.Windows.Forms.StatusBar();
this.SuspendLayout();
//
// 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 = 22;
this.label4.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 = 21;
this.label3.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 = 20;
this.label2.Text = "监听端口:";
//
// 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 = 19;
this.label1.Text = "服务器:";
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(256, 256);
this.btnStop.Name = "btnStop";
this.btnStop.TabIndex = 18;
this.btnStop.Text = "关闭连接";
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// btnSend
//
this.btnSend.Location = new System.Drawing.Point(144, 256);
this.btnSend.Name = "btnSend";
this.btnSend.TabIndex = 17;
this.btnSend.Text = "发送信息";
this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
//
// btnConnect
//
this.btnConnect.Location = new System.Drawing.Point(32, 256);
this.btnConnect.Name = "btnConnect";
this.btnConnect.TabIndex = 16;
this.btnConnect.Text = "请求连接";
this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);
//
// 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 = 15;
this.txtPort.Text = "19811";
//
// txtServer
//
this.txtServer.Location = new System.Drawing.Point(72, 16);
this.txtServer.Name = "txtServer";
this.txtServer.TabIndex = 14;
this.txtServer.Text = "127.0.0.1";
//
// 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 = 13;
this.rtbSend.Text = "";
//
// 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 = 12;
this.rtbReceive.Text = "";
//
// 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 = 23;
this.statusBar1.Text = "statusBar1";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(360, 309);
this.Controls.Add(this.statusBar1);
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.btnConnect);
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.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnConnect_Click(object sender, System.EventArgs e)
{
try
{
hostIPAddress=IPAddress.Parse(txtServer.Text);
}
catch{MessageBox.Show("请输入正确的IP地址格式。");}
try
{
Server=new IPEndPoint(hostIPAddress,Int32.Parse(txtPort.Text));
sock=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
sock.Connect(Server);
statusBar1.Text="与主机"+txtServer.Text+"端口"+txtPort.Text+"连接成功";
Thread thread=new Thread(new ThreadStart(ThreadProc));
thread.Start();
}
catch(Exception ee){MessageBox.Show(ee.Message);}
}
private void ThreadProc()
{
while(true)
{
Byte[] ByteRecv=new Byte[256];
sock.Receive(ByteRecv,ByteRecv.Length,0);
string strRecv=Encoding.BigEndianUnicode.GetString(ByteRecv);
rtbReceive.AppendText(strRecv+"\r\n");
}
}
private void btnSend_Click(object sender, System.EventArgs e)
{
try
{
string strSend ="Client--->"+rtbSend.Text+"\r\n";
Byte[] ByteSend = Encoding.BigEndianUnicode.GetBytes(strSend);
sock.Send(ByteSend,ByteSend.Length,0);
}
catch{MessageBox.Show("连接尚未建立,无法发送.");}
}
private void btnStop_Click(object sender, System.EventArgs e)
{
try
{
sock.Close();
statusBar1.Text="与主机"+txtServer.Text+"端口"+txtPort.Text+"断开连接";
}
catch{MessageBox.Show("连接尚未建立,关闭无效");}
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
try
{
sock.Close();
}
catch{}
}
}
}
.NET 框架的 Socket 类实际上是 Winsock32 API 提供的套接字服务的托管代码版本。其中Socket 类为网络通信提供了一套丰富的方法和属性,大多数情况下,Socket 类方法只是将数据封送到它们的本机Win32 副本中并处理任何必要的安全检查。Socket 类允许使用 ProtocolType 枚举中所列出的任何一种协议执行异步和同步数据传输。Socket 类遵循异步方法的 .NET Framework 命名模式;例如,同步 Receive 方法对应于异步 BeginReceive 和 EndReceive 方法。
事实上Socket可以象流Stream一样被视为一个应用程序端(客户端)和远程服务器端之间数据通道,通过这个通道来对数据进行读取(接收)和写入(发送)。
异步模式所提供的革新之一就是调用方确定特定调用是否应是异步的。对于被调用的对象,没有必要执行附加的编程来用于支持其客户端的异步行为;在该模式中异步委托提供此功能。
如果应用程序在执行期间只需要一个线程,请使用我在《实例解析SOCKET编程模型》中介绍的方法,这些方法适用于单线程同步操作模式。同步操作模式对执行网络操作的函数(如 Send 和 Receive)的调用一直等到操作完成后才将控制返回给调用程序。
若要在执行过程中使用单独的线程处理通信,请使用下面的方法,这些方法适用于异步操作模式。异步操作模式对执行网络操作的函数的调用立即返回。
如果当前使用的是面向连接的协议(如 TCP),则可使用 Socket、BeginConnect 和 EndConnect 方法来连接侦听主机。通过使用 BeginSend 和 EndSend 方法,或者使用 BeginReceive 和 EndReceive 方法,可以进行异步数据通信。可以使用 BeginAccept 和 EndAccept 处理传入的连接请求。
如果当前使用的是无连接协议(如 UDP),则可以使用 BeginSendTo 和 EndSendTo 来发送数据报,而使用 BeginReceiveFrom 和 EndReceiveFrom 来接收数据报。
当数据发送和数据接收完成之后,可使用 Shutdown 方法来禁用 Socket。在调用 Shutdown 之后,可调用 Close 方法来释放与 Socket 关联的所有资源。
Socket 类允许使用 SetSocketOption 方法来配置 Socket。可使用 GetSocketOption 方法来检索这些设置。
注意 如果编写较简单的应用程序,而且只需同步数据传输,则可以考虑使用 TcpClient、TcpListener 和 UdpClient。这些类为 Socket 通信提供了更简单、对用户更友好的接口。
从TCP/IP模型上来看, 像 System.Net命名空间中的HttpWebReqeust类和HttpWebResponse类属于请求/响应层。TcpClient、TcpListener 和 UdpClient这些类属于应用协议层,处中间。而Socket类处于传输层,是最底层。当其上面的请求/响应层和应用协议层不能满足应用程序的特殊需要时,就需要使用传输层进行Socket套接字编程。
异步服务器套接字使用 .NET Framework 异步编程模型处理网络服务请求。Socket 类遵循标准 .NET Framework 异步命名模式;例如,同步 Accept 方法对应异步 BeginAccept 和 EndAccept 方法。
异步服务器套接字需要一个开始接受网络连接请求的方法,一个处理连接请求并开始接收网络数据的回调方法以及一个结束接收数据的回调方法。本节将进一步讨论所有这些方法。
在下面的源码中,为开始接受网络连接请求,方法 StartListening 初始化 Socket,然后使用 BeginAccept 方法开始接受新连接。当套接字上接收到新连接请求时,将调用接受回调方法。它负责获取将处理连接的 Socket 实例,并将 Socket 提交给将处理请求的线程。接受回调方法实现 AsyncCallback 委托;它返回 void,并带一个 IAsyncResult 类型的参数。下面的示例是接受回调方法的外壳程序: private void AcceptCallBack(IAsyncResult ar){}
BeginAccept 方法带两个参数:指向接受回调方法的 AsyncCallback 委托和一个用于将状态信息传递给回调方法的对象。在下面的示例中,侦听 Socket 通过状态参数传递给回调方法。本示例创建一个 AsyncCallback 开始一个异步操作来接受一个传入的连接尝试 listeningSocket.BeginAccept(new AsyncCallback(AcceptCallBack),listeningSocket);//
异步套接字使用系统线程池中的线程处理传入的连接。一个线程负责接受连接,另一线程用于处理每个传入的连接,还有一个线程负责接收连接数据。这些线程可以是同一个线程,具体取决于线程池所分配的线程。System.Threading.ManualResetEvent 类挂起主线程的执行并在执行可以继续时发出信号。
接受回调方法(即前例中的 acceptCallback)负责向主应用程序发出信号,让它继续执行处理、建立与客户端的连接并开始异步读取客户端数据。下面的示例是 acceptCallback 方法实现的第一部分。该方法的此节向主应用程序线程发出信号,让它继续处理并建立与客户端的连接。
开始从客户端套接字接收数据的 acceptCallback 方法的此节首先初始化 StateObject 类的一个实例,然后调用 BeginReceive 方法以开始从客户端套接字异步读取数据。需要为异步套接字服务器实现的 final 方法是返回客户端发送的数据的读取回调方法。与接受回调方法一样,读取回调方法也是一个 AsyncCallback 委托。该方法将来自客户端套接字的一个或多个字节读入数据缓冲区,然后再次调用 BeginReceive 方法,直到客户端发送的数据完成为止。
创建线程时,将使用采用 ThreadStart 委托作为其唯一参数的构造函数创建 Thread 类的新实例。但线程在调用 Start 方法前不会开始执行。调用 Start 后,将从由 ThreadStart 委托引用的方法的第一行开始执行。如下例所示: Thread thread=new Thread(new ThreadStart(ThreadProc));
thread.Start();
在以下的源码中我们使用了ManualResetEvent 来允许线程通过发信号互相通信。通常,此通信涉及一个线程在其他线程进行之前必须完成的任务。
当线程开始一个活动(此活动必须在其他线程进行之前完成)时,它调用 Reset 将 ManualResetEvent 设置为非终止状态。此线程可被视为控制 ManualResetEvent。调用 ManualResetEvent 上的 WaitOne 的线程将阻塞,并等待信号。当控制线程完成活动时,它调用 Set 以发出等待线程可以继续进行的信号。并释放所有等待线程。
一旦它被终止,ManualResetEvent 将保持终止状态,直到它被手动重置。即对 WaitOne 的调用将立即返回。
可以通过将布尔值传递给构造函数来控制 ManualResetEvent 的初始状态,如果初始状态处于终止状态,为 true;否则为 false。
//以下是异步聊天服务器端详细实现方法
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 handler;
private Socket mySocket;
private static ManualResetEvent Done=new ManualResetEvent(false);
private const int BufferSize=256;
private byte[] buffer=new byte[BufferSize];
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");*/
Done.Reset(); //将状态设为非终止
listeningSocket.BeginAccept(new AsyncCallback(AcceptCallBack),listeningSocket);//开始一个异步操作来接受一个传入的连接尝试
Done.WaitOne(); //阻塞当前线程,直到当前线程收到信号。
}
//}
}
private void AcceptCallBack(IAsyncResult ar)//ar表示异步操作的状态。
{
Done.Set();//设为终止
mySocket=(Socket)ar.AsyncState; //获取状态
handler=mySocket.EndAccept(ar); //异步接受传入的连接尝试,并创建新的 Socket 来处理远程主机通信,获取结果
try
{
byte[] byteData=Encoding.BigEndianUnicode.GetBytes("准备完毕,可以通话"+"\r\n");
//调用SendCallBack异步发送数据,
handler.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallBack),handler);
}
catch(Exception ee){MessageBox.Show(ee.Message);}
Thread thread=new Thread(new ThreadStart(ThreadRev));
thread.Start();
}
private void SendCallBack(IAsyncResult ar)
{
try
{
handler=(Socket)ar.AsyncState; //获取状态
int bytesSent=handler.EndSend(ar);//结束挂起的异步发送,返回向 Socket 发送的字节数
}
catch{}
}
private void ThreadRev()
{
handler.BeginReceive(buffer,0,BufferSize,0,new AsyncCallback(ReadCallBack),handler);
}
private void ReadCallBack(IAsyncResult ar)
{
int bytesRead=handler.EndReceive(ar); //结束挂起的异步读取,返回接收到的字节数。
StringBuilder sb=new StringBuilder(); //接收数据的可变字符字符串,在通过追加、移除、替换或插入字符而创建它后可以对它进行修改。
sb.Append(Encoding.BigEndianUnicode.GetString(buffer,0,bytesRead));//追加字符串
string content=sb.ToString(); //转换为字符串
sb.Remove(0,content.Length); //清除sb内容
rtbReceive.AppendText(content+"\r\n");
handler.BeginReceive(buffer,0,BufferSize,0,new AsyncCallback(ReadCallBack),handler);
}
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);
handler.BeginSend(ByteSend,0,ByteSend.Length,0,new AsyncCallback(SendCallBack),handler);
}
catch{MessageBox.Show("连接尚未建立,无法发送.");}
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
try
{
listeningSocket.Close();//在窗口关闭之前关闭Scoket连接并释放所有关联的资源。
}
catch{}
}
}
}
异步客户端套接字在等待网络操作完成时不挂起应用程序。相反,它使用标准 .NET Framework 异步编程模型在一个线程上处理网络连接,而应用程序继续在原始线程上运行。异步套接字适用于大量使用网络或不能等待网络操作完成才能继续的应用程序。
Socket 类遵循异步方法的 .NET Framework 命名模式;例如,同步 Receive 方法对应异步 BeginReceive 和 EndReceive 方法。
异步操作要求回调方法返回操作结果。如果应用程序不需要知道结果,则不需要任何回调方法。本节中的代码示例阐释如何使用某个方法开始与网络设备的连接并使用回调方法结束连接,如何使用某个方法开始发送数据并使用回调方法完成发送,以及如何使用某个方法开始接收数据并使用回调方法结束接收数据。
异步套接字使用多个系统线程池中的线程处理网络连接。一个线程负责初始化数据的发送或接收;其他线程完成与网络设备的连接并发送或接收数据。在程序源码中,System.Threading.ManualResetEvent 类的实例用于挂起主线程的执行并在执行可以继续时发出信号。
在客户端源码中,为了将异步套接字连接到网络设备,Socket 方法初始化一个 Socket,然后调用 BeginConnect 方法,传递表示网络设备的远程终结点、连接回调方法以及状态对象(即客户端 Socket,用于在异步调用之间传递状态信息)。该示例实现 Connect 方法以将指定的 Socket 连接到指定的终结点。它采用一个名为 connectDone 的全局 ManualResetEvent: public IAsyncResult BeginConnect(
EndPoint remoteEP,
AsyncCallback callback,
object state
);
连接回调方法 ConnectCallback 实现 AsyncCallback 委托。它在远程设备可用时连接到远程设备,然后通过设置 ManualResetEvent connectDone 向应用程序线程发出连接完成的信号。下面的客户端源码中实现了 ConnectCallback 方法。
Send 示例方法以 ASCII 格式对指定的字符串数据进行编码,并将其异步发送到指定的套接字所表示的网络设备。
发送回调方法 SendCallback 实现 AsyncCallback 委托。它在网络设备准备接收时发送数据。下面的源码中实现了 SendCallback 方法。它采用一个名为 sendDone 的全局 ManualResetEvent。
从客户端套接字读取数据需要一个在异步调用之间传递值的状态对象。下面的类是用于从客户端套接字接收数据的示例状态对象。它包含以下各项的字段:客户端套接字,用于接收数据的缓冲区,以及用于保存传入数据字符串的 StringBuilder。将这些字段放在该状态对象中,使这些字段的值在多个调用之间得以保留,以便从客户端套接字读取数据。
public class StateObject {
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
} //为简单起见,客户端源码中并未创建此类
Receive 方法示例设置状态对象,然后调用 BeginReceive 方法从客户端套接字异步读取数据。
接收回调方法 ReceiveCallback 实现 AsyncCallback 委托。它接收来自网络设备的数据并生成消息字符串。它将来自网络的一个或多个数据字节读入数据缓冲区,然后再次调用 BeginReceive 方法,直到客户端发送的数据完成为止。从客户端读取所有数据后,ReceiveCallback 通过设置 ManualResetEvent sendDone 向应用程序线程发出数据完成的信号。
//以下是客户端详细实现代码
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_client
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnStop;
private System.Windows.Forms.Button btnSend;
private System.Windows.Forms.TextBox txtPort;
private System.Windows.Forms.TextBox txtServer;
private System.Windows.Forms.RichTextBox rtbSend;
private System.Windows.Forms.RichTextBox rtbReceive;
private System.Windows.Forms.StatusBar statusBar1;
private System.Windows.Forms.Button btnConnect;
private IPAddress hostIPAddress;
private IPEndPoint Server;
private Socket sock;
private const int BufferSize=256;
private byte[] buffer=new byte[BufferSize];
private static ManualResetEvent connectDone=new ManualResetEvent(false);
private static ManualResetEvent sendDone=new ManualResetEvent(false);
/// <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.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.btnStop = new System.Windows.Forms.Button();
this.btnSend = new System.Windows.Forms.Button();
this.btnConnect = new System.Windows.Forms.Button();
this.txtPort = new System.Windows.Forms.TextBox();
this.txtServer = new System.Windows.Forms.TextBox();
this.rtbSend = new System.Windows.Forms.RichTextBox();
this.rtbReceive = new System.Windows.Forms.RichTextBox();
this.statusBar1 = new System.Windows.Forms.StatusBar();
this.SuspendLayout();
//
// 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 = 22;
this.label4.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 = 21;
this.label3.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 = 20;
this.label2.Text = "监听端口:";
//
// 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 = 19;
this.label1.Text = "服务器:";
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(256, 256);
this.btnStop.Name = "btnStop";
this.btnStop.TabIndex = 18;
this.btnStop.Text = "关闭连接";
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// btnSend
//
this.btnSend.Location = new System.Drawing.Point(144, 256);
this.btnSend.Name = "btnSend";
this.btnSend.TabIndex = 17;
this.btnSend.Text = "发送信息";
this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
//
// btnConnect
//
this.btnConnect.Location = new System.Drawing.Point(32, 256);
this.btnConnect.Name = "btnConnect";
this.btnConnect.TabIndex = 16;
this.btnConnect.Text = "请求连接";
this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);
//
// 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 = 15;
this.txtPort.Text = "19811";
//
// txtServer
//
this.txtServer.Location = new System.Drawing.Point(72, 16);
this.txtServer.Name = "txtServer";
this.txtServer.TabIndex = 14;
this.txtServer.Text = "127.0.0.1";
//
// 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 = 13;
this.rtbSend.Text = "";
//
// 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 = 12;
this.rtbReceive.Text = "";
//
// 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 = 23;
this.statusBar1.Text = "statusBar1";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(360, 309);
this.Controls.Add(this.statusBar1);
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.btnConnect);
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.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnConnect_Click(object sender, System.EventArgs e)
{
try
{
hostIPAddress=IPAddress.Parse(txtServer.Text);
}
catch{MessageBox.Show("请输入正确的IP地址格式。");}
try
{
Server=new IPEndPoint(hostIPAddress,Int32.Parse(txtPort.Text));
sock=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
sock.BeginConnect(Server,new AsyncCallback(ConnectCallBack),sock);
}
catch(Exception ee){MessageBox.Show(ee.Message);}
}
private void ConnectCallBack(IAsyncResult ar)
{
try
{
Socket client=(Socket)ar.AsyncState; //获取状态
client.EndConnect(ar);
try
{
byte[] byteData=Encoding.BigEndianUnicode.GetBytes("准备完毕,可以通话"+"\r\n");
sock.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallBack),sock);
}
catch(Exception ee){MessageBox.Show(ee.Message);}
statusBar1.Text="与主机"+txtServer.Text+"端口"+txtPort.Text+"连接成功";
Thread thread=new Thread(new ThreadStart(ThreadProc));
thread.Start(); //开始接收数据线程
connectDone.Set(); //将指定事件的状态设置为终止。
}
catch{}
}
private void SendCallBack(IAsyncResult ar)
{
try{
Socket client=(Socket)ar.AsyncState;
sendDone.Set();
}
catch(Exception ee){MessageBox.Show(ee.Message);}
}
private void ThreadProc()
{
try
{
sock.BeginReceive(buffer,0,BufferSize,0,new AsyncCallback(ReceiveCallBack),sock);
}
catch(Exception ee){MessageBox.Show(ee.Message);}
}
private void ReceiveCallBack(IAsyncResult ar)
{
try
{
Socket client=(Socket)ar.AsyncState;
int bytesRead=client.EndReceive(ar);//结束挂起的异步读取。返回接收到的字节数。
StringBuilder sb=new StringBuilder();
sb.Append(Encoding.BigEndianUnicode.GetString(buffer,0,bytesRead));//储存数据
string content=sb.ToString(); //转换为字符串
sb.Remove(0,content.Length); //清除sb内容
rtbReceive.AppendText(content+"\r\n");
client.BeginReceive(buffer,0,BufferSize,0,new AsyncCallback(ReceiveCallBack),client);
}
catch{}
}
private void btnSend_Click(object sender, System.EventArgs e)
{
try
{
string strSend ="Client--->"+rtbSend.Text+"\r\n";
Byte[] ByteSend = Encoding.BigEndianUnicode.GetBytes(strSend);
sock.BeginSend(ByteSend,0,ByteSend.Length,0,new AsyncCallback(SendCallBack),sock);
}
catch{MessageBox.Show("连接尚未建立,无法发送.");}
}
private void btnStop_Click(object sender, System.EventArgs e)
{
try
{
sock.Close();
statusBar1.Text="与主机"+txtServer.Text+"端口"+txtPort.Text+"断开连接";
}
catch{MessageBox.Show("连接尚未建立,关闭无效");}
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
try
{
sock.Close();
}
catch{}
}
}
}
posted on 2004-12-02 17:47
吴文力
阅读(713)
评论(0)
编辑
收藏
网摘
新用户注册
刷新评论列表
标题
姓名
主页
Email
(博主才能看到)
验证码
*
看不清,换一张
[
登录
][
注册
]
内容(请不要发表任何与政治相关的内容)
网站首页
新闻频道
社区
小组
博问
网摘
人才
找找看
Remember Me?
登录
使用高级评论
新用户注册
返回页首
恢复上次提交
[使用Ctrl+Enter键可以直接提交]
Google站内搜索
China-pub 计算机图书网上专卖店!6.5万品种 2-8折!
近千种 9-95 新二手计算图书火热销售中!
开发者征途系统新作:《设计模式——基于C#的工程化实现及扩展》
相关文章:
相关链接:
最新IT新闻:
51.com否认彩虹软件改名
彩虹QQ正式更名51彩虹 称“上QQ从51彩虹开始”
Jadu: 将 PHP 编译成 .NET
开心网遭多个山寨版复制围抢用户
微软表示Windows 7将直接在CPU上跑DirectX 10