Socket网络编程(三):TcpListener、TcpClient
2010-09-27 16:48 czyhsl 阅读(788) 评论(0) 编辑 收藏 举报使用Socket基础类(Socket网络编程(二))可以提高应用程序性能,但对于一般的小程序,使用TcpListener、TcpClient则更加方便,它提供了更多的接口。具体步骤和Socket基础类中差不多,只需要做简单修改即可。
服务端:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
namespace SocketTest
{
public partial class Server : Form
{
Thread serverThread;
Thread clientThread;
TcpListener serverTcp;
TcpClient clientTcp;
public Server()
{
InitializeComponent();
}
private void ServerStart()
{
//创建IPEndPoint实例
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 6001);
serverTcp = new TcpListener(ipep);
serverTcp.Start();
while (true)
{
try
{
//在套接字上接收接入的连接
clientTcp = serverTcp.AcceptTcpClient();
clientThread = new Thread(new ThreadStart(ReceiveData));
clientThread.Start();
}
catch (Exception ex)
{
MessageBox.Show("listening Error: " + ex.Message);
}
}
}
private void ReceiveData()
{
bool keepAlive = true;
TcpClient s = clientTcp;
NetworkStream ns = s.GetStream();
Byte[] buffer = new Byte[1024];
//根据收听到的客户端套接字向客户端发送信息
IPEndPoint clientip = (IPEndPoint)s.Client.RemoteEndPoint;
lstServer.Items.Add("Client:" + clientip.Address + "("+clientip.Port+")");
string welcome = "Welcome to my test sever ";
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(welcome);
//s.Send(data, data.Length, SocketFlags.None);
ns.Write(data,0, data.Length);
while (keepAlive)
{
//在套接字上接收客户端发送的信息
int bufLen = 0;
try
{
bufLen = s.Available;
ns.Read(buffer, 0, bufLen);
if (bufLen == 0)
continue;
}
catch (Exception ex)
{
MessageBox.Show("Receive Error:" + ex.Message);
return;
}
clientip = (IPEndPoint)s.Client.RemoteEndPoint;
string clientCommand = System.Text.Encoding.ASCII.GetString(buffer).Substring(0, bufLen);
lstServer.Items.Add(clientCommand + "("+clientip.Address + ":"+clientip.Port+")");
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
serverThread = new Thread(new ThreadStart(ServerStart));
serverThread.Start();
lstServer.Items.Add("Server Start .....");
}
}
}
客户端:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Client
{
public partial class Client : Form
{
TcpClient clientTcp;
Thread clientThread;
NetworkStream ns;
public Client()
{
InitializeComponent();
}
private void ConnectToServer()
{
byte[] data = new byte[1024];
//创建一个套接字
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6001);
clientTcp = new TcpClient();
//将套接字与远程服务器地址相连
try
{
clientTcp.Connect(ipep);
}
catch (SocketException ex)
{
MessageBox.Show("connect error: " + ex.Message);
return;
}
ns = clientTcp.GetStream();
while (true)
{
//接收服务器信息
int bufLen = 0;
try
{
bufLen = clientTcp.Available;
ns.Read(data, 0, bufLen);
if (bufLen == 0)
{
continue;
}
}
catch (Exception ex)
{
MessageBox.Show("Receive Error:" + ex.Message);
return;
}
string clientCommand = System.Text.Encoding.ASCII.GetString(data).Substring(0, bufLen);
lstClient.Items.Add(clientCommand);
}
}
private void button1_Click(object sender, EventArgs e)
{
clientThread = new Thread(new ThreadStart(ConnectToServer));
clientThread.Start();
}
private void btnSend_Click(object sender, EventArgs e)
{
//向服务器发送信息
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(txtClient.Text);
ns.Write(data, 0, data.Length);
}
}
}
很显然,在这里就不能使用Socket中的Send()、Receive()方法,而只能去使用NetworkStream的Read()、Write()方法。两种实现的代码差异,可以具体去比较。