u3d下的Tcp和Udp通信的两种写法

本文介绍了在Unity3D中使用Socket进行TCP和UDP通信的两种方法,包括服务端和客户端的实现。TCP通信需要建立连接,提供安全但较慢的数据传输,而UDP通信则无需连接,速度快但可能丢包。实现时需注意端口对应、阻塞函数的使用和资源释放。
摘要由CSDN通过智能技术生成

1、使用Socket的Tcp

    服务端:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

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


public class ScocketServer : MonoBehaviour {

    private Thread _StartServer;

    byte[] byte_receive;
    Socket RecieveSocket;
    IPEndPoint iep;
    EndPoint ep;
    // Use this for initialization
    void Start () {

        //Socket Tcp
        byte_receive = new byte[100];
        iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1001);
        RecieveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        RecieveSocket.Bind(iep);
        RecieveSocket.Listen(10);

        _StartServer = new Thread(StartServer);
        _StartServer.Start();

    }
	
	// Update is called once per frame
	void Update () {

    }

    void StartServer()
    {
        Debug.Log("服务端:等人...");
        Socket tempSocket = RecieveSocket.Accept();//阻断
        Debug.Log("服务端:有人来了");
        while (true)
        {
            int datalength = tempSocket.Receive(byte_receive);
            if (datalength != 0)
            {
                string msg = Encoding.Unicode.GetString(byte_receive);
                Debug.Log("服务端:我收到消息:" + msg);
            }
        }
    }

    private void OnApplicationQuit()
    {
        if (_StartServer != null)//关闭线程
        {
            _StartServer.Interrupt();
            _StartServer.Abort();
        }
        //最后关闭socket
        if (RecieveSocket != null)
            RecieveSocket.Close();
    }
}

    客户端:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

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

public class ScocketClient : MonoBehaviour {

    private Thread ClientThread;
    int MsgIndex;
    Socket ClientSocket;
    IPEndPoint ep;
    string msg;
    byte[] byteSendingArray;
    // Use this for initialization
    void Start () {
        ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1001);
         byteSendingArray = new byte[100];
        MsgIndex = 0;
    }
	
	// Update is called once per frame
	void Update () {
		if(Input.GetKeyDown(KeyCode.Alpha1))
            {
                SendMsg();
            }
	}

    private voi
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值