本实例是一个基于TCP的简单通讯实例,分为服务器端和客户端,服务器端监听客户端的连接请求,客户端将信息发送给服务器端,而服务器端则回复客户端发送的信息以达到通讯测试:
服务器端代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace SimpleTcpServer
{
class Program
{
static void Main(string[] args)
{
//接收到的数据
int receive;
//定义数据缓冲区
byte [] date=new byte[1024];
//设置终端连接,接收任意请求的IP地址客户终端
IPEndPoint MyIpEndpoint = new IPEndPoint(IPAddress.Any, 13000);
//新建一个服务器套接字
Socket MySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定服务端套接字
MySocket.Bind(MyIpEndpoint);
//监听
MySocket.Listen(10);
Console.WriteLine("Waitting for a message from client!");
//获取客户端套接字
Socket Client = MySocket.Accept();
//获取客户端终点
IPEndPoint ClientEndPoint =(IPEndPoint)Client.RemoteEndPoint;
Console.WriteLine("Connect with {0} port {1}",ClientEndPoint.Address,ClientEndPoint.Port.ToString());
//将要发送到客户端的信息进行编码
date = Encoding.ASCII.GetBytes("Welcome to my Server");
//发送信息到客户端
Client.Send(date, date.Length, SocketFlags.None);
//如果接收的信息长度为0,则自动退出循环
while (true)
{
receive = Client.Receive(date);
if (receive==0)
{
break;
}
//接收到的字符
string ReceiveString = Encoding.UTF8.GetString(date, 0, receive);
Console.WriteLine(ReceiveString);
//发送信息到客户端
Client.Send(date, receive, SocketFlags.None);
}
Console.WriteLine("DisConnected with {0}", ClientEndPoint.Address);
Client.Close();
MySocket.Close();
}
}
}