leiqunqing
2026-02-06 15b3879cd259108e7ebb755fe02c190f28f1e20c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
 
namespace WIDESEAWCS_Common
{
    public class TcpClientExample
    {
        public static string Start(string Ip, int Prot)
        {
            try
            {
                // 1. 创建 Socket 对象
                Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // 1.配置超时(核心:避免Receive无限阻塞)
                clientSocket.SendTimeout = 3000; // 连接超时3秒
                clientSocket.ReceiveTimeout = 3000; // 连接超时3秒
                // 2. 连接服务器(IP 为服务器的 IP,端口与服务器一致)
                IPAddress serverIp = IPAddress.Parse(Ip); // 本地测试用 127.0.0.1,实际替换为服务器 IP
                IPEndPoint serverEndPoint = new IPEndPoint(serverIp, Prot);
                clientSocket.Connect(serverEndPoint);
                //Console.WriteLine("已成功连接到服务器");
 
                // 将字符串转换为字节数组并发送
                byte[] sendBuffer = Encoding.UTF8.GetBytes("start");
                clientSocket.Send(sendBuffer);
                // 接收服务器回复
                byte[] recvBuffer = new byte[1024];
                int recvLen = clientSocket.Receive(recvBuffer);
                string recvMsg = Encoding.UTF8.GetString(recvBuffer, 0, recvLen);
                //Console.WriteLine($"收到服务器回复:{recvMsg}");
 
                // 4. 关闭连接
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
                //Console.WriteLine("已断开与服务器的连接");
 
                return recvMsg;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return "";
            }
        }
    }
}