赞
踩
在C#中进行TCP开发,通常使用System.Net.Sockets
命名空间下的TcpListener
和TcpClient
类。以下是一个简单的TCP服务器和客户端示例。
TCP服务器端:
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
-
- class TcpServer
- {
- private TcpListener tcpListener;
- private int port;
-
- public TcpServer(int port)
- {
- this.port = port;
- }
-
- public void StartServer()
- {
- tcpListener = new TcpListener(IPAddress.Any, port);
- tcpListener.Start();
- Console.WriteLine($"Server started on port {port}.");
- while (true)
- {
- TcpClient client = tcpListener.AcceptTcpClient();
- HandleClient(client);
- }
- }
-
- private void HandleClient(TcpClient client)
- {
- NetworkStream stream = client.GetStream();
- byte[] bytes = Encoding.UTF8.GetBytes("Hello from the server!");
- stream.Write(bytes, 0, bytes.Length);
- stream.Close();
- client.Close();
- }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- TcpServer server = new TcpServer(8000);
- server.StartServer();
- }
- }
TCP客户端:
- using System;
- using System.IO;
- using System.Net.Sockets;
- using System.Text;
-
- class TcpClient
- {
- private TcpClient tcpClient;
- private NetworkStream stream;
- private int port;
- private string host;
-
- public TcpClient(string host, int port)
- {
- this.host = host;
- this.port = port;
- }
-
- public void Connect()
- {
- tcpClient = new TcpClient(host, port);
- stream = tcpClient.GetStream();
- Console.WriteLine("Connected to server.");
- string response = GetResponse();
- Console.WriteLine($"Response from server: {response}");
- tcpClient.Close();
- }
-
- private string GetResponse()
- {
- byte[] bytes = new byte[1024];
- int bytesRead = stream.Read(bytes, 0, bytes.Length);
- return Encoding.UTF8.GetString(bytes, 0, bytesRead);
- }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- TcpClient client = new TcpClient("localhost", 8000);
- client.Connect();
- }
- }
在这个例子中,服务器监听8000端口,并接受任何客户端的连接。客户端连接到本机的8000端口,并接收来自服务器的问候消息。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。