unity socket通信
客户端unityusing 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(&#34;port&#34;, SSL? &#34;443&#34; : &#34;8848&#34;));
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(&#34;Open your web browser and navigate to &#34; +
// (SSL? &#34;https&#34; : &#34;http&#34;) + &#34;://127.0.0.1:&#34; + PORT + &#39;/&#39;);
ch.closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public class ServerInitializer extends ChannelInitializer<SocketChannel> {
private static final String WEBSOCKET_PATH = &#34;/websocket&#34;;
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, &#34;UTF-8&#34;);
System.out.println(this.getStrDate() + ctx.channel().remoteAddress() + &#34;\t&#34; + body);
}
}完成通信
unity日志
netty日志
页:
[1]