TCP传输数据

发布时间:2024年01月22日

TCP客户端

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;

public class TCPClient
{
    /// <summary>
    /// 客户端
    /// </summary>
    private TcpClient tcpClient;
    private NetworkStream stream;

    public TCPClient(string ip, int port)
    {
        try
        {
            //初始化客户端
            tcpClient = new TcpClient(ip, port); // 连接到指定的服务器地址和端口
            stream = tcpClient.GetStream();

            // 开始接收数据
            byte[] buffer = new byte[1024];
            stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(ReceiveCallback), buffer);
        }
        catch (Exception e)
        {
            Debug.Log("错误Error: " + e.Message);
        }
    }

    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="message"></param>
    public void Send(string message)
    {
        if (stream == null)
        {
            Debug.Log("Error: TCP connection is not established.");
            return;
        }

        byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
        stream.Write(data, 0, data.Length);
        Debug.Log("Sent message: " + message);
    }
    int a;
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Send("我是小偷" + a++);
        }
    }
    /// <summary>
    /// 接收消息
    /// </summary>
    /// <param name="ar"></param>
    private void ReceiveCallback(IAsyncResult ar)
    {
        int bytesRead = stream.EndRead(ar);
        if (bytesRead == 0)
        {
            return;
        }
        byte[] data = (byte[])ar.AsyncState;
        string message = System.Text.Encoding.UTF8.GetString(data, 0, bytesRead);
        Debug.Log("收到消息Received message: " + message);

        // 继续监听下一条消息
        stream.BeginRead(data, 0, data.Length, new AsyncCallback(ReceiveCallback), data);
    }

    public void SocketQuit()
    {
        if (tcpClient != null)
        {
            tcpClient.Close();
        }
    }
}

TCP服务器

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

public class TCPServer
{
    /// <summary>
    /// 客户端
    /// </summary>
    private Socket socketClient;
    /// <summary>
    /// 服务器
    /// </summary>
    private Socket socketServer;
    /// <summary>
    /// 监听线程
    /// </summary>
    private Thread thread;
    private Thread r_thread;

    /// <summary>
    /// 开启服务器监听
    /// </summary>
    /// <param name="ip">ip</param>
    /// <param name="port">端口</param>
    public TCPServer(string ip, int port)
    {
        socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPAddress iPAddress = IPAddress.Parse(ip);
        EndPoint endPoint = new IPEndPoint(iPAddress, port);
        socketServer.Bind(endPoint);
        socketServer.Listen(5);
        //监听连接
        thread = new Thread(ReceiveFromClient);
        thread.IsBackground = true;
        thread.Start(socketServer);
    }

    /// <summary>
    /// 监听连接的客户端
    /// </summary>
    /// <param name="obj"></param>
    private void ReceiveFromClient(object obj)
    {
        try
        {
            Socket socketWatch = obj as Socket;
            while (true)
            {
                socketClient = socketWatch.Accept();
                r_thread = new Thread(ReceiveMsg);
                r_thread.IsBackground = true;
                r_thread.Start(socketClient);
            }
        }
        catch (System.Exception e)
        {
            Debug.Log(e.Message);
        }
    }

    /// <summary>
    /// 接收数据
    /// </summary>
    /// <param name="obj"></param>
    public void ReceiveMsg(object obj)
    {
        Socket socket = obj as Socket;
        while (true)
        {
            byte[] buffer = new byte[1024];
            int length = socket.Receive(buffer);
            if (length == 0)
            {
                return;
            }
            byte[] dataCache = new byte[length];

            for (int i = 0; i < length; i++)
            {
                //存储数据
                dataCache[i] = buffer[i];
            }
            string message = System.Text.Encoding.UTF8.GetString(dataCache);
            Debug.Log("收到消息Received message: " + message);
        }
    }

   public void Send(string sendStr)
   {
        //清空发送缓存
        byte[] sendData = new byte[1024];
        //数据类型转换
        sendData = Encoding.UTF8.GetBytes(sendStr);
        //发送
        socketClient.Send(sendData, sendData.Length, SocketFlags.None);
        Debug.Log("Sent message: " + sendStr);
    }

    /// <summary>
    /// 关闭
    /// </summary>
    public void SocketQuit()
    {
        if (socketClient != null)
        {
            socketClient.Close();
        }
        if (thread != null)
        {
            thread.Interrupt();
            thread.Abort();
        }
        if (r_thread != null)
        {
            r_thread.Interrupt();
            r_thread.Abort();
        }
        if (socketServer != null)
        {
            socketServer.Close();
        }

        Debug.Log("关闭服务器");
    }
}

文章来源:https://blog.csdn.net/liuhongze98/article/details/135752859
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。