简单的unity 客户端与服务端互相发送消息

这篇博客介绍了如何使用Unity作为客户端,通过C#实现服务器,进行双向消息传递。服务器端采用C#编写,负责接收和处理客户端发送的消息字符串。在Unity客户端,创建了专门的client脚本,并在主场景中进行了集成应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

服务器部分用C#写的

首先是 游戏client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Collections;

namespace wsocketbydx
{
    class GameClient
    {
        public static Hashtable allClient = new Hashtable();   
        public static List<string> ipList = new List<string>();
        private TcpClient _client;
        public string _clientIP;
        public string _clientNick;
        private byte[] data;
        
        public GameClient(TcpClient client)
        {
            this._client = client;
            this._clientIP = client.Client.RemoteEndPoint.ToString();
            if (allClient.Count <= 2)
            {
                allClient.Add(this._clientIP, this);
                ipList.Add(this._clientIP);
                data = new byte[this._client.ReceiveBufferSize];
                client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), RceiveMessage, null);
                this.sendMessage("login success");
            }
            else
            {
                this.sendMessage("connect num is max,so connect failed");
            }
        }
        public void RceiveMessage(IAsyncResult ar)
        {
            int bytesread;
            try
            {
                lock (this._client.GetStream())
                {
                    bytesread = this._client.GetStream().EndRead(ar);
      
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值