Unity使用C#实现简单Scoket连接及服务端与客户端通讯

服务端代码:

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

/***
*    Title: "***"
*     主题:***
*    description:
*     功能:YYY
*    Data:2018
*    version(版本):
*    Modify recoder(修改记录):
*/

public class MyServer : MonoBehaviour {

    Thread connectThread;//当前服务端监听子线程
    public string address;//当前地址
    public int port;//当前本地端口
    TcpClient romoteClient;//远程客户端

    // Use this for initialization
    void Start()
    {
        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();
        Debug.Log("服务端-->客户端完成,开启tcp连接监听");
        //如果有远程客户端连接,此时得到其对象用于通讯
        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;
                }
                string 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!"));
        }
    }

    int number = 0;
    public void OnClick()
    {
        if(romoteClient!=null)
        {
            romoteClient.Client.Send(Encoding.UTF8.GetBytes(number++.ToString()));
        }
    }

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

}

客户端代码:

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

/***
*    Title: "***"
*     主题:***
*    description:
*     功能:YYY
*    Data:2018
*    version(版本):
*    Modify recoder(修改记录):
*/

public class MyClient : MonoBehaviour {

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



    int number = 0;
    public void OnClick()
    {
        try
        {
            string clientStr = number++.ToString();
            //获取当前客户端的流对象,然后将要发送的字符串转化为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
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值