mastertravels77 发表于 2022-10-31 19:53

unity socket通信

客户端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;
      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';
            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.readBytes(req);
      String body = new String(req, "UTF-8");
      System.out.println(this.getStrDate() + ctx.channel().remoteAddress() + "\t" + body);
    }
}完成通信




unity日志



netty日志
页: [1]
查看完整版本: unity socket通信