Unity与java后端UDP通信

1. unity客户端代码:

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

public class Udp : MonoBehaviour
{
    static Socket client; // client
    static Thread reciveThread;
    static Thread sendThread;

    static EndPoint server;

    void Start()
    {
        server = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8800);
        client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        client.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6666));//绑定端口号和IP
        reciveThread = new Thread(ReciveMsg);//开启接收消息线程
        reciveThread.Start();
        sendThread = new Thread(()=>SendMsg("hello, first time"));//开启发送消息线程
        sendThread.Start();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.M)) {
            String msg = "time:" + Time.deltaTime;
            SendMsg(msg);
        }
    }

    void OnDestroy() {
         client.Close();
    }


    /// 
    /// 向特定ip的主机的端口发送数据报
    /// 
    static void SendMsg(String msg)
    {
        client.SendTo(Encoding.UTF8.GetBytes(msg), server);
    }
    /// 
    /// 接收发送给本机ip对应端口号的数据报
    /// 
    static void ReciveMsg()
    {
        while (true)
        {
            Thread.Sleep(100);
            EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
            byte[] buffer = new byte[1024];
            int length = client.ReceiveFrom(buffer, ref point);//接收数据报
            string message = Encoding.UTF8.GetString(buffer,0,length);
            Debug.Log(message);
            
        }
    }
}

2. java服务端代码:

package cn.com.zh.udp;

import cn.com.zh.qmcq.All;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPServer {
    public static void main(String[] args) throws IOException {
        /*
         * 接收客户端发送的数据
         */
        //1.创建服务器端DatagramSocket,指定端口
        DatagramSocket socket=new DatagramSocket(8800);
        //2.创建数据报,用于接收客户端发送的数据
        byte[] data =new byte[1024];//创建字节数组,指定接收的数据包的大小
        System.out.println("****服务器启动,等待客户端连接****");
        int count=1;
        while(true) {
            DatagramPacket packet = new DatagramPacket(data, data.length);
            socket.receive(packet);

            InetAddress address = packet.getAddress();  // 接收到哪个ip发来的数据
            int port = packet.getPort();    // 对方使用哪个端口发送的
            if (All.clientMap.containsKey(address.getHostAddress()+"_"+port)) {
                System.out.println("客户端已经存在");
                continue;
            }
            All.clientMap.put(address.getHostAddress()+"_"+port, null);
            UDPServerThread serverThread = new UDPServerThread(packet, socket);
            serverThread.start();
            System.out.println("客户端数量:" + count++);
        }
    }
}

3.维护每个客户端连接

package cn.com.zh.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPServerThread extends Thread{
    DatagramPacket packet;
    DatagramSocket socket;

    public UDPServerThread(DatagramPacket packet, DatagramSocket socket) {
        super();
        this.packet = packet;
        this.socket = socket;
    }

    @Override
    public void run(){
        try {
            //获取客户端信息
            byte[] data = packet.getData();
            String info1 = new String(data, 0, packet.getLength());
            System.out.println("我是服务器,客户端说:" + info1);
            //响应客户端
            InetAddress address = packet.getAddress();  // 接收到哪个ip发来的数据
            int port = packet.getPort();    // 对方使用哪个端口发送的

            while (true) {
                // TODO do business
                Thread.sleep(3000);
                byte[] data1 = ("欢迎您!" + System.currentTimeMillis()).getBytes();
                DatagramPacket packet1 = new DatagramPacket(data1, data1.length, address, port);
                socket.send(packet1);
            }
        }catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

你可能感兴趣的:(unity,unity,java,udp)