
利用C#实现TCP/IP协议客户端与服务器的代码示例
5星
- 浏览量: 0
- 大小:None
- 文件类型:None
简介:
本代码示例展示了如何使用C#编程语言建立基于TCP/IP协议的网络通信,包括创建简单的客户端和服务器端程序。通过该示例,开发者可以学习到基础的套接字操作、连接管理及数据传输技术。适合初学者快速上手网络编程实践。
基于C#的TCP/IP协议客户端和服务端代码实现如下:
服务器端代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
namespace TcpServerApp
{
class Program
{
static void Main(string[] args)
{
// 创建一个socket对象,用于监听传入连接。
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
try
{
// 绑定端点并开始监听传入连接。
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
Console.WriteLine(等待客户端的连接...);
// 接受来自客户端的新连接请求。
Socket handler = listener.Accept();
DataHandler(handler, ipAddress.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void DataHandler(Socket handler, string ip)
{
try
{
while (true)
{
// 接收客户端发送的数据。
byte[] bytes = new Byte[1024];
int bytesRec = handler.Receive(bytes);
Console.WriteLine(从{0}接收到数据:{1}, ip, Encoding.ASCII.GetString(bytes, 0, bytesRec));
string response = 已接收您的消息;
byte[] msg = System.Text.Encoding.ASCII.GetBytes(response);
// 将响应发送回客户端。
handler.Send(msg);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
```
客户端代码:
```csharp
using System;
using System.Net.Sockets;
namespace TcpClientApp
{
class Program
{
static void Main(string[] args)
{
// 创建一个socket对象,用于与服务器通信。
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(localhost);
IPAddress ipAddress = ipHostInfo.AddressList[0];
// 连接到指定的IP地址和端口。
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
client.Connect(remoteEP);
Console.WriteLine($连接到{client.RemoteEndPoint});
string data = 发送给服务器的消息;
byte[] msg = Encoding.ASCII.GetBytes(data);
// 将消息发往服务端。
client.Send(msg);
// 接收从服务端返回的确认信息。
int bytesRec = client.Receive(buffer);
Console.WriteLine(接收的数据:{0}, Encoding.ASCII.GetString(buffer, 0, bytesRec));
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
```
以上代码展示了如何使用C#实现TCP/IP协议的客户端和服务端。服务器监听一个特定的IP地址和端口,等待来自客户端的消息,并发送响应消息给客户端;而客户端则连接到服务端并进行通信。
关键点解释:
1. `Socket`类用于创建网络套接字。
2. 通过调用`Bind()`方法将socket绑定至指定的本地IP地址与端口号组合而成的IPEndPoint对象,然后调用`Listen()`来开始监听传入连接请求。
3. 使用`Accept()`函数等待客户端发起连接,并返回一个新的Socket实例用于与该特定客户端通信。
4. 客户端使用connect方法将自己绑定到服务器的IP和端口上以建立一个socket连接。
全部评论 (0)


