C# tcp短链接源码
时间: 2025-01-26 19:39:31 浏览: 37
### C# 实现 TCP 短连接的源代码示例
对于创建基于 C# 的 TCP 短连接应用,可以利用 `System.Net.Sockets` 命名空间中的类来构建客户端和服务端程序。下面提供了一个简单的例子用于展示如何建立并关闭一次性的短连接。
#### 客户端代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class TcpClientExample {
public static void Main() {
try {
// 创建TcpClient对象实例
using (TcpClient client = new TcpClient()) {
// 连接到服务器
client.Connect(IPAddress.Parse("127.0.0.1"), 80);
// 获取网络流
NetworkStream stream = client.GetStream();
// 发送数据到服务端
string message = "Hello Server";
byte[] data = Encoding.ASCII.GetBytes(message);
stream.Write(data, 0, data.Length);
Console.WriteLine($"Sent: {message}");
// 接收来自服务端的数据
data = new Byte[256];
int bytes = stream.Read(data, 0, data.Length);
string responseData = Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine($"Received: {responseData}");
// 关闭资源
stream.Close();
client.Close();
}
} catch (ArgumentNullException e) {
Console.WriteLine("ArgumentNullException: " + e);
} catch (SocketException e) {
Console.WriteLine("SocketException: " + e);
}
Console.WriteLine("\n Press Enter to continue...");
Console.Read();
}
}
```
此段代码展示了怎样通过 `TcpClient` 类发起一个至本地主机上运行的服务端口为80的服务端的一次性连接请求,在发送一条消息之后立即断开连接[^1]。
#### 服务端代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SimpleTcpServer {
private const int portNum = 80;
public static void StartListening() {
byte[] bytes = new Byte[1024];
// 设置监听器
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener server = null;
try {
server = new TcpListener(localAddr, portNum);
server.Start();
while(true){
Console.Write("Waiting for a connection... ");
// 执行阻塞操作直到接收到新的连接
using(TcpClient client = server.AcceptTcpClient()){
Console.WriteLine("Connected!");
DataExchange(client);
// 断开当前会话后的清理工作
client.Close();
}
}
} catch (SocketException e) {
Console.WriteLine("SocketException: {0}", e);
} finally{
if(server != null)
server.Stop();
}
}
private static void DataExchange(TcpClient tcpclnt){
NetworkStream ns = tcpclnt.GetStream();
byte[] bufferIn = new byte[tcpclnt.ReceiveBufferSize];
int bytesRead = ns.Read(bufferIn, 0, (int)tcpclnt.ReceiveBufferSize);
string receivedText = Encoding.UTF8.GetString(bufferIn, 0, bytesRead);
Console.WriteLine($"Received Text= {receivedText}");
// 向客户端回显相同的信息作为响应
byte[] sendBytes = Encoding.UTF8.GetBytes(receivedText);
ns.Write(sendBytes, 0, sendBytes.Length);
Console.WriteLine("Echoed back.");
}
}
// 调用StartListening方法启动服务端
SimpleTcpServer.StartListening();
```
上述服务端逻辑会在指定地址和端口号处等待传入的连接尝试;每当一个新的客户机成功建立了连接,则处理该客户的输入输出,并随后终止此次交互以准备迎接下一个可能到来的新访客。
阅读全文
相关推荐
















