C#通过Socket类实现TCP通信,首先服务器绑定IP和端口并监听,客户端发起连接,双方通过Send/Receive收发数据,最后关闭连接。

C# 进行网络编程主要依赖于 System.Net 和 System.Net.Sockets 命名空间,其中最核心的是使用 Socket 类实现基于 TCP/IP 协议的通信。本文将通过一个简单的客户端-服务器模型,详解如何用 C# 实现 TCP 通信,并给出可运行的代码示例。
Socket(套接字)是网络通信的端点,它允许程序通过网络发送和接收数据。在 TCP/IP 模型中,TCP 提供面向连接、可靠的数据传输服务。C# 中通过 Socket 类封装了底层的网络操作,开发者可以创建服务器监听连接,也可以创建客户端发起请求。
TCP 通信的基本流程如下:
服务器负责监听端口,等待客户端连接,并处理客户端发来的消息。以下是使用 Socket 编写的简单 TCP 服务器示例:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
<p>class TcpServer
{
static void Main()
{
// 定义监听的IP和端口
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 8885;
IPEndPoint endPoint = new IPEndPoint(ip, port);</p><pre class='brush:php;toolbar:false;'> // 创建Socket
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
// 绑定并监听
serverSocket.Bind(endPoint);
serverSocket.Listen(10); // 最多允许10个等待连接
Console.WriteLine("服务器已启动,等待客户端连接...");
// 接受客户端连接
Socket clientSocket = serverSocket.Accept();
Console.WriteLine($"客户端 {clientSocket.RemoteEndPoint} 已连接");
// 接收数据
byte[] buffer = new byte[1024];
int bytesRead = clientSocket.Receive(buffer);
string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("收到消息: " + message);
// 回复客户端
string response = "消息已收到";
byte[] responseData = Encoding.UTF8.GetBytes(response);
clientSocket.Send(responseData);
// 关闭连接
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
catch (Exception ex)
{
Console.WriteLine("服务器错误: " + ex.Message);
}
finally
{
serverSocket.Close();
}
Console.ReadLine();
}}
客户端主动连接服务器,发送消息并接收响应。以下是对应的客户端代码:
PHP是一种功能强大的网络程序设计语言,而且易学易用,移植性和可扩展性也都非常优秀,本书将为读者详细介绍PHP编程。 全书分为预备篇、开始篇和加速篇三大部分,共9章。预备篇主要介绍一些学习PHP语言的预备知识以及PHP运行平台的架设;开始篇则较为详细地向读者介绍PKP语言的基本语法和常用函数,以及用PHP如何对MySQL数据库进行操作;加速篇则通过对典型实例的介绍来使读者全面掌握PHP。 本书
472
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
<p>class TcpClientApp
{
static void Main()
{
// 服务器地址和端口
IPAddress serverIp = IPAddress.Parse("127.0.0.1");
int port = 8885;
IPEndPoint serverEndPoint = new IPEndPoint(serverIp, port);</p><pre class='brush:php;toolbar:false;'> // 创建Socket
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
// 连接服务器
clientSocket.Connect(serverEndPoint);
Console.WriteLine("已连接到服务器");
// 发送消息
string message = "你好,服务器!";
byte[] data = Encoding.UTF8.GetBytes(message);
clientSocket.Send(data);
// 接收回复
byte[] buffer = new byte[1024];
int bytesRead = clientSocket.Receive(buffer);
string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("服务器回复: " + response);
}
catch (Exception ex)
{
Console.WriteLine("客户端错误: " + ex.Message);
}
finally
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
Console.ReadLine();
}}
虽然上述示例展示了基本通信流程,但在实际开发中还需注意以下几点:
例如,使用 TcpListener 可以让服务器代码更简洁:
TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8885);
listener.Start();
using TcpClient client = listener.AcceptTcpClient();
// 使用 NetworkStream 读写数据
基本上就这些。通过掌握 Socket 编程基础,你可以构建聊天程序、文件传输工具或自定义协议服务。不复杂但容易忽略的是编码一致性和连接生命周期管理。
以上就是C#如何进行网络编程?Socket与TCP/IP通信编程实例详解的详细内容,更多请关注php中文网其它相关文章!
编程怎么学习?编程怎么入门?编程在哪学?编程怎么学才快?不用担心,这里为大家提供了编程速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号