| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading.Tasks;
- namespace TCPIPTest
- {
- internal class TcpClientClass
- {
- TcpClient client = null;
- NetworkStream stream = null;
- public bool CreatTcpClient(string serverIp, int port)
- {
- bool result = false;
- // 连接到服务器
- try
- {
- client = new TcpClient(serverIp, port);
- Console.WriteLine("已连接到服务器");
- stream = client.GetStream();
- result = true;
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Connect to server failed:{ex.Message}");
- }
- return result;
- }
- public void SendMessage(ushort message)
- {
- byte[] data = BitConverter.GetBytes(message);
- stream.Write(data, 0, data.Length);
- Console.WriteLine($"{DateTime.Now.ToString("O")}已发送消息: {message}");
- }
- public byte[] ReadMessage()
- {
- // 接收响应
- byte[] buffer = new byte[256];
- int bytesRead = stream.Read(buffer, 0, buffer.Length);
- return buffer;
- }
- }
- }
|