找回密码
 立即注册
查看: 260|回复: 0

unity socket通信

[复制链接]
发表于 2022-10-31 19:53 | 显示全部楼层 |阅读模式
客户端unity

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

public class HttpClient : MonoBehaviour
{
    public static HttpClient Instance;
    private const string IP = "127.0.0.1";
    private const int PORT = 8848;
    Thread threadReceive;

    private Socket client;

    private void Awake()
    {
        if (!Instance)
        {
            DontDestroyOnLoad(this);
            Instance = this;
            connect();
        }
    }

    void Update()
    {
    }

    void connect()
    {
        try
        {
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.Connect(IP, PORT);
            Debug.Log("连接服务器成功\r\n");

            threadReceive = new Thread(ReceiveMsg);
            threadReceive.IsBackground = true;
            threadReceive.Start();
        }
        catch
        {
            Debug.Log("连接服务器失败\r\n");
        }
    }

    public void Send(int type, string roomName = "", string s = "")
    {
        try
        {
            Debug.Log(client.RemoteEndPoint+ "send: " + type + ":" + roomName + ":" + s);
        }
        catch
        {
            connect();
        }
        if (client == null || client.RemoteEndPoint == null)
        {
            connect();
        }
        int c = type + '0';
        string msg = (char)c + ":" + roomName+":"+s;
        byte[] buffer = Encoding.UTF8.GetBytes(msg);
        client.Send(buffer);
    }

    void ReceiveMsg()
    {
        byte[] buffer = new byte[1024 * 1024];
        int len = 0;
        while (true)
        {
            len = client.Receive(buffer);
            if (len == 0) threadReceive.Abort();
            string msg = Encoding.UTF8.GetString(buffer, 0, len);
            Debug.Log("ReceiveMsg = " + msg);
            int type = msg[0]-'0';
            if (type < 5) Lobby.Instance.onResponse(msg);
            else Online.Instance.onResponse(msg);
        }
    }

    void OnApplicationQuit()
    {
        if (threadReceive != null) threadReceive.Abort();
        if (client != null)
        {
            client.Shutdown(SocketShutdown.Both);
            client.Close();
        }
    }
}
服务端netty

public final class Server {
     static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "443" : "8848"));
     try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ServerInitializer(sslCtx));

            Channel ch = b.bind(PORT).sync().channel();

//            System.out.println("Open your web browser and navigate to " +
//                    (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/');
            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
}
public class ServerInitializer extends ChannelInitializer<SocketChannel> {
    private static final String WEBSOCKET_PATH = "/websocket";
    private final SslContext sslCtx;

    public ServerInitializer(SslContext sslCtx) {
        this.sslCtx = sslCtx;
    }

    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        if (this.sslCtx != null) {
            pipeline.addLast(new ChannelHandler[]{this.sslCtx.newHandler(ch.alloc())});
        }

        pipeline.addLast(new ChannelHandler[]{new ServerHandler()});
    }
}

public class ServerHandler extends ChannelInboundHandlerAdapter {
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf)msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, "UTF-8");
        System.out.println(this.getStrDate() + ctx.channel().remoteAddress() + "\t" + body);
    }
}完成通信




unity日志



netty日志

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-11-15 12:30 , Processed in 0.090020 second(s), 26 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表