unity 简单Socket通信

首先,创建两个工程,分别是Sever和Client。

Sever工程:

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

public class Sever : MonoBehaviour
{
    public static Sever instance;
    private void Awake()
    {
        instance = this;
    }

    Thread connectThread;//当前服务端监听子线程
    TcpClient romoteClient;//远程客户端
    public string address;//当前地址
    public int port;//当前本地端口
    private string msg;//接收到的消息

    void Start()
    {
        StartConnect();
    }

    public void StartConnect()
    {
        connectThread = new Thread(InitServerSocket);
        connectThread.Start();
    }

    /// <summary>
    /// 实例化服务端Socket
    /// </summary>
    public void InitServerSocket()
    {
        int bufferSize = 8192;//缓冲区大小
        IPAddress ip = IPAddress.Parse(address);
        //新建TCP连接,并开启监听子线程
        TcpListener tcpListener = new TcpListener(ip, port);
        tcpListener.Start();
        //如果有远程客户端连接,此时得到其对象用于通讯
        romoteClient = tcpListener.AcceptTcpClient();
        Debug.Log("客户端连接开始 本地地址端口: " + romoteClient.Client.LocalEndPoint + "  远程客户端地址端口: " + romoteClient.Client.RemoteEndPoint);
        NetworkStream stream = romoteClient.GetStream();
        do
        {
            try
            {
                //获取与客户端连接数据
                byte[] buffer = new byte[bufferSize];
                int byteRead = stream.Read(buffer, 0, bufferSize);
                if (byteRead == 0)
                {
                    Debug.Log("客户端断开");
                    break;
                }
                msg = Encoding.UTF8.GetString(buffer, 0, byteRead);
                Debug.Log("接收到客户端的数据: " + msg + "   数据长度: " + byteRead + "字节");
                //这里 收到客户端数据 可以做一些处理
            }
            catch (Exception ex)
            {
                Debug.Log("客户端异常: " + ex.Message);
                //客户端出现异常或者断开的时候,关闭线程防止溢出
                tcpListener.Stop();
                break;
            }
        } while (true);
    }

    /// <summary>
    /// 服务器端根据当前连接的远程客户端发送消息
    /// </summary>
    public void SendMessageToClient()
    {
        if (romoteClient != null)
        {
            romoteClient.Client.Send(Encoding.UTF8.GetBytes("Hello Client ,This is Server!"));
        }
    }

    /// <summary>
    /// 销毁时关闭监听线程及连接
    /// </summary>
    void OnDestroy()
    {
        if (romoteClient != null)
            romoteClient.Close();
        if (connectThread != null)
            connectThread.Abort();
    }
}

Client工程:

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 Client : MonoBehaviour
{
    public static Client instance;
    private void Awake()
    {
        instance = this;
    }

    public string serverAddress;//服务器地址
    public int port;//服务器端口
    private TcpClient localClient;//当前tcp客户端
    private Thread receiveThread;//接收服务器消息线程
    private byte[] resultBuffer = new byte[1024];//服务器返回流字节
    private string resultStr;//服务器返回字符串

    void Start()
    {
        //连接至服务端
        InitClientSocket();
    }

    /// <summary>
    /// 销毁时操作
    /// </summary>
    private void OnDestroy()
    {
        if (localClient != null)
            localClient.Close();
        if (receiveThread != null)
            receiveThread.Abort();
    }

    /// <summary>
    /// 客户端实例化Socket连接
    /// </summary>
    private void InitClientSocket()
    {
        localClient = new TcpClient();
        try
        {
            //当前客户端连接的服务器地址与远程端口
            localClient.Connect(IPAddress.Parse(serverAddress), port);
            //开始接收服务器消息子线程
            receiveThread = new Thread(SocketReceiver);
            receiveThread.Start();
            Debug.Log("客户端-->服务端完成,开启接收消息线程");
        }
        catch (Exception ex)
        {
            Debug.Log("客户端连接服务器异常: " + ex.Message);
        }
        Debug.Log("连接到服务器 本地地址端口:" + localClient.Client.LocalEndPoint + "  远程服务器端口:" + localClient.Client.RemoteEndPoint);
    }

    /// <summary>
    /// 客户端发送消息到服务器
    /// </summary>
    public void SendMessageToServer(string clientStr)
    {
        try
        {
            //获取当前客户端的流对象,然后将要发送的字符串转化为byte[]写入发送
            NetworkStream stream = localClient.GetStream();
            byte[] buffer = Encoding.UTF8.GetBytes(clientStr);
            stream.Write(buffer, 0, buffer.Length);
        }
        catch (Exception ex)
        {
            Debug.Log("发送消息时服务器产生异常: " + ex.Message);
        }
    }

    /// <summary>
    /// 客户端检测收到服务器信息子线程
    /// </summary>
    private void SocketReceiver()
    {
        if (localClient != null)
        {
            while (true)
            {
                if (localClient.Client.Connected == false)
                    break;
                //在循环中,
                localClient.Client.Receive(resultBuffer);
                resultStr = Encoding.UTF8.GetString(resultBuffer);
                Debug.Log("客户端收到服务器消息 : " + resultStr);
            }
        }
    }
}

具体操作步骤(适合新手):

1.查看当前本机IP地址(不会的百度)并设置;端口号随便写,8888,8899都行。

2.运行服务器+客户端。

3.可通过服务端(SendMessageToClient())或客户端(SendMessageToServer(string clientStr))两个方法互相发送字符串。

4.接收到的这个字符串就可以做一些相应的处理了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

橘长长长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值