TCP传输数据

TCP客户端

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

public class TCPClient
{
    /// 
    /// 客户端
    /// 
    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);
        }
    }

    /// 
    /// 发送消息
    /// 
    /// 
    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++);
        }
    }
    /// 
    /// 接收消息
    /// 
    /// 
    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
{
    /// 
    /// 客户端
    /// 
    private Socket socketClient;
    /// 
    /// 服务器
    /// 
    private Socket socketServer;
    /// 
    /// 监听线程
    /// 
    private Thread thread;
    private Thread r_thread;

    /// 
    /// 开启服务器监听
    /// 
    /// ip
    /// 端口
    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);
    }

    /// 
    /// 监听连接的客户端
    /// 
    /// 
    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);
        }
    }

    /// 
    /// 接收数据
    /// 
    /// 
    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);
    }

    /// 
    /// 关闭
    /// 
    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("关闭服务器");
    }
}

你可能感兴趣的:(tcp/ip,restful,网络协议,unity,c#)