unity3d 简易socket通信,接收发送消息

这篇博客展示了如何在Unity3D中使用C#实现简单的Socket通信,包括客户端和服务器端的设置。客户端通过TcpClient连接到服务器,并发送、接收消息。服务器端通过TcpListener监听连接,并处理来自客户端的消息。代码示例详细解释了登录、发送和接收消息的流程。

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

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

public class SocketClient : MonoBehaviour
{


    public static SocketClient instance;
    public int portNo = 9999;
    private TcpClient _client;
    byte[] data;
    public string url = "127.0.0.1";

    public void Awake()
    {
        instance = this;
    }

    public string idtext = "";
    bool connect = false;  //只允许登录一次  
    public void login()
    {
        if (idtext != "" && !connect)
        {
            connect = true;
            this._client = new TcpClient();
            this._client.Connect(url, portNo);
            data = new byte[this._client.ReceiveBufferSize];
            SendMessage(idtext);
            this._client.GetStream().BeginRead(this.data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize),
            ReceiveMessage, null);

        }
        else
        {
            Debug.Log("connect failed or connected");
        }
    }
    public void ReceiveMessage(IAsyncResult ar)
    {
        try
        {
            int bytesRead;
            bytesRead = this._client.GetStream().EndRead(ar);
            if (bytesRead < 1)
            {
                return;
            }
            else
            {
                Debug.Log("Client_ReceiveMessage:"+System.Text.Encoding.UTF8.GetString(data, 0, bytesRead));
                string message = System.Text.Encoding.UTF8.GetString(data, 0, bytesRead);
            }
        }
        catch (Exception ex)
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值