123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- using System.Threading.Tasks;
- using DevExpress.XtraEditors;
- namespace XzXdDw
- {
- public class TcpServer
- {
- private TcpListener listener;
- public event Action<byte[]> OnDataReceived;
- public void Start(int port, string ip = null)
- {
- Task.Run(() =>
- {
- if (string.IsNullOrWhiteSpace(ip))
- {
- listener = new TcpListener(IPAddress.Any, port);
- }
- else
- {
- listener = new TcpListener(IPAddress.Parse(ip), port);
- }
- listener.Start();
- L1:
- TcpClient client = null;
- try
- {
- client = listener.AcceptTcpClient();
- }
- catch (Exception ex)
- {
- return;
- }
- while (true)
- {
- try
- {
- var stream = client.GetStream();
- byte[] lenData = new byte[4];
- int readLen = stream.Read(lenData, 0, 4);
- if (readLen == 0)
- goto L1;
- byte[] data = new byte[BitConverter.ToInt32(lenData, 0)];
- readLen = stream.Read(data, 0, data.Length);
- if (readLen == 0)
- goto L1;
- OnDataReceived?.Invoke(data);
- }
- catch (Exception ex)
- {
- goto L1;
- }
- }
- });
- }
- public void StopListening()
- {
- listener?.Stop();
- listener = null;
- }
- /// <summary>
- /// TCP发送数据
- /// </summary>
- /// <param name="serverIP"></param>
- /// <param name="port"></param>
- /// <param name="strjson"></param>
- /// <returns></returns>
- public async void SendData(string serverIP, int port, string strjson)
- {
- await Task.Run(async () =>
- {
- try
- {
- using (TcpClient client = new TcpClient())
- {
- await client.ConnectAsync(serverIP, port);
- NetworkStream stream = client.GetStream();
- byte[] dataToSend = Encoding.UTF8.GetBytes(strjson);
- // 将数据发送到服务器
- stream.Write(dataToSend, 0, dataToSend.Length);
- }
- }
- catch (Exception ex)
- {
-
- }
- });
- }
- }
- }
|