您的位置:首页 > 理论基础 > 计算机网络

2.3 TcpListener同步基础服务器开发

2009-11-12 16:13 267 查看
TcpListener基础服务器开发(这里只说服务器端开发,客户端的开发将在“2.4 TcpClient同步客户端开发 ”里面讲述)

在C#里面TcpListener类封装了Socket的同步和异步的相关方法,TcpListener提供了比Socket类更有好的开发接口。

1.端口监听:TcpListenerl类提供了Start方法和AcceptSocket方法实现端口的监听和接收客户端的连接请求。

这两个方法的原型如下

public  void  Start() //启动监听

public   Socket  AcceptSocket()  //接收用户的连接请求,并返回一个Socket套接字用以处理客户的连接。该方法是同步调用,当执行到该方法时会一直等待,直到接收到用户的请求时才返回。


2.发送数据和接收数据和“C# Socket与实现 ”里面的发送和接收数据的方法一样,这里就不再多说了,可以参考。

3.基础服务器开始实例代码:

首先建立一个项目名为ServerTcp。下面是服务器的界面设计代码:

SeverForm.Designer.cs文件

namespace ServerTcp
{
partial class SeverForm
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;

/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows 窗体设计器生成的代码

/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.StartListenButton = new System.Windows.Forms.Button();
this.PortTextBox = new System.Windows.Forms.TextBox();
this.HostStateRichTextBox = new System.Windows.Forms.RichTextBox();
this.label2 = new System.Windows.Forms.Label();
this.CommunicateMessgeRichTextBox = new System.Windows.Forms.RichTextBox();
this.label3 = new System.Windows.Forms.Label();
this.SendRichTextBox = new System.Windows.Forms.RichTextBox();
this.SendButton = new System.Windows.Forms.Button();
this.StopListenButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(35, 31);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(41, 12);
this.label1.TabIndex = 0;
this.label1.Text = "端口号";
//
// StartListenButton
//
this.StartListenButton.Location = new System.Drawing.Point(298, 26);
this.StartListenButton.Name = "StartListenButton";
this.StartListenButton.Size = new System.Drawing.Size(89, 34);
this.StartListenButton.TabIndex = 1;
this.StartListenButton.Text = "开始监听";
this.StartListenButton.UseVisualStyleBackColor = true;
this.StartListenButton.Click += new System.EventHandler(this.StartListenButton_Click);
//
// PortTextBox
//
this.PortTextBox.Location = new System.Drawing.Point(82, 28);
this.PortTextBox.Name = "PortTextBox";
this.PortTextBox.Size = new System.Drawing.Size(163, 21);
this.PortTextBox.TabIndex = 2;
this.PortTextBox.Text = "8080";
//
// HostStateRichTextBox
//
this.HostStateRichTextBox.Location = new System.Drawing.Point(371, 91);
this.HostStateRichTextBox.Name = "HostStateRichTextBox";
this.HostStateRichTextBox.Size = new System.Drawing.Size(191, 230);
this.HostStateRichTextBox.TabIndex = 3;
this.HostStateRichTextBox.Text = "";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(369, 76);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(53, 12);
this.label2.TabIndex = 4;
this.label2.Text = "主机状态";
//
// CommunicateMessgeRichTextBox
//
this.CommunicateMessgeRichTextBox.Location = new System.Drawing.Point(37, 91);
this.CommunicateMessgeRichTextBox.Name = "CommunicateMessgeRichTextBox";
this.CommunicateMessgeRichTextBox.Size = new System.Drawing.Size(305, 230);
this.CommunicateMessgeRichTextBox.TabIndex = 5;
this.CommunicateMessgeRichTextBox.Text = "";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(35, 76);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(53, 12);
this.label3.TabIndex = 6;
this.label3.Text = "通话信息";
//
// SendRichTextBox
//
this.SendRichTextBox.Location = new System.Drawing.Point(37, 353);
this.SendRichTextBox.Name = "SendRichTextBox";
this.SendRichTextBox.Size = new System.Drawing.Size(525, 123);
this.SendRichTextBox.TabIndex = 7;
this.SendRichTextBox.Text = "";
//
// SendButton
//
this.SendButton.Location = new System.Drawing.Point(230, 494);
this.SendButton.Name = "SendButton";
this.SendButton.Size = new System.Drawing.Size(143, 45);
this.SendButton.TabIndex = 8;
this.SendButton.Text = "发送信息";
this.SendButton.UseVisualStyleBackColor = true;
this.SendButton.Click += new System.EventHandler(this.SendButton_Click);
//
// StopListenButton
//
this.StopListenButton.Location = new System.Drawing.Point(450, 28);
this.StopListenButton.Name = "StopListenButton";
this.StopListenButton.Size = new System.Drawing.Size(84, 32);
this.StopListenButton.TabIndex = 9;
this.StopListenButton.Text = "停止监听";
this.StopListenButton.UseVisualStyleBackColor = true;
this.StopListenButton.Click += new System.EventHandler(this.StopListenButton_Click);
//
// SeverForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(605, 583);
this.Controls.Add(this.StopListenButton);
this.Controls.Add(this.SendButton);
this.Controls.Add(this.SendRichTextBox);
this.Controls.Add(this.label3);
this.Controls.Add(this.CommunicateMessgeRichTextBox);
this.Controls.Add(this.label2);
this.Controls.Add(this.HostStateRichTextBox);
this.Controls.Add(this.PortTextBox);
this.Controls.Add(this.StartListenButton);
this.Controls.Add(this.label1);
this.Name = "SeverForm";
this.Text = "Server";
this.ResumeLayout(false);
this.PerformLayout();

}

#endregion

private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button StartListenButton;
private System.Windows.Forms.TextBox PortTextBox;
private System.Windows.Forms.RichTextBox HostStateRichTextBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.RichTextBox CommunicateMessgeRichTextBox;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.RichTextBox SendRichTextBox;
private System.Windows.Forms.Button SendButton;
private System.Windows.Forms.Button StopListenButton;
}
}


接下来是主要的逻辑控制代码如下:

SeverForm.cs文件

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;
using System.Net.Sockets;
using System.Threading;

namespace ServerTcp
{
public partial class SeverForm : Form
{
private int port;
private TcpListener Listener;
private Socket handler;
private const int BufferSize = 1024;
private Thread thread = null;

public SeverForm()
{
InitializeComponent();
}

private void StartListenButton_Click(object sender, EventArgs e)
{
if (Listener != null)
{
MessageBox.Show("监听已经开始,无需重新监听!");
return;
}

try
{
port = Int32.Parse(PortTextBox.Text.Trim());
Listener = new TcpListener(port);
Listener.Start();
HostStateRichTextBox.AppendText("主机开始监听.../r/n");
thread =new Thread(new ThreadStart(Accept));
thread.Start();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

}

//线程同步代码
private void Accept()
{
while (true)
{
handler = Listener.AcceptSocket();
if (handler.Connected)
{
Control.CheckForIllegalCrossThreadCalls = false;
HostStateRichTextBox.AppendText("与客户端建立连接/r/n");
try
{
byte[] recBuffer = new byte[BufferSize];
string recStr = null;
int recBytes = 0;
NetworkStream netStream = new NetworkStream(handler);
while (true)
{
recStr = handler.RemoteEndPoint.ToString() + "/r/n";
recBytes = netStream.Read(recBuffer, 0, recBuffer.Length);
recStr += System.Text.Encoding.BigEndianUnicode.GetString(recBuffer);
CommunicateMessgeRichTextBox.AppendText(recStr);
CommunicateMessgeRichTextBox.AppendText("/r/n");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

private void StopListenButton_Click(object sender, EventArgs e)
{
try
{
if (!(thread == null))
{
thread.Abort();
thread = null;
}

if (!(handler == null))
{
handler.Close();
handler = null;
}

if (!(Listener == null))
{
Listener.Stop();
Listener = null;
HostStateRichTextBox.AppendText("停止监听。/r/n");
}
else
{
MessageBox.Show("监听还未开始,无法停止!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private void SendButton_Click(object sender, EventArgs e)
{
try
{
string sendStr = SendRichTextBox.Text.Trim();
if (sendStr.Equals(""))
{
MessageBox.Show("发送消息不能为空!");
return;
}
CommunicateMessgeRichTextBox.AppendText(Dns.GetHostName() + "/r/n" + sendStr + "/r/n");
NetworkStream netStream = new NetworkStream(handler);
byte[] SendBuffer = System.Text.Encoding.BigEndianUnicode.GetBytes(sendStr.ToCharArray());
netStream.Write(SendBuffer, 0, SendBuffer.Length);
SendRichTextBox.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

public  void  Dispose()
{
if (thread != null)
{
thread.Abort();
}
base.Dispose();
}
}
}


本程序在Windows 7下用VS 2008调试通过并对前面出现的许多异常进行了处理,谢谢关注。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: