欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity3d使用Socket与java服务器通信

程序员文章站 2022-03-26 14:40:19
...

转自:https://blog.csdn.net/AngelMyMei/article/details/40742825

---------------------------客户端----------------------------------------

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Threading;
  8. using UnityEngine;
  9. /*
  10. *
  11. *Socket客户端通信类
  12. *
  13. * lm
  14. */
  15. public class SocketHelper
  16. {
  17. private static SocketHelper socketHelper=new SocketHelper();
  18. private Socket socket;
  19. //饿汉模式
  20. public static SocketHelper GetInstance()
  21. {
  22. return socketHelper;
  23. }
  24. private SocketHelper() {
  25. //采用TCP方式连接
  26. socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  27. //服务器IP地址
  28. IPAddress address = IPAddress.Parse("127.0.0.1");
  29. //服务器端口
  30. IPEndPoint endpoint = new IPEndPoint(address,8000);
  31. //异步连接,连接成功调用connectCallback方法
  32. IAsyncResult result = socket.BeginConnect(endpoint, new AsyncCallback(ConnectCallback), socket);
  33. //这里做一个超时的监测,当连接超过5秒还没成功表示超时
  34. bool success = result.AsyncWaitHandle.WaitOne(5000, true);
  35. if (!success)
  36. {
  37. //超时
  38. Closed();
  39. Debug.Log("connect Time Out");
  40. }
  41. else
  42. {
  43. //与socket建立连接成功,开启线程接受服务端数据。
  44. Thread thread = new Thread(new ThreadStart(ReceiveSorket));
  45. thread.IsBackground = true;
  46. thread.Start();
  47. }
  48. }
  49. private void ConnectCallback(IAsyncResult asyncConnect)
  50. {
  51. Debug.Log("connect success");
  52. }
  53. private void ReceiveSorket()
  54. {
  55. //在这个线程中接受服务器返回的数据
  56. while (true)
  57. {
  58. if (!socket.Connected)
  59. {
  60. //与服务器断开连接跳出循环
  61. Debug.Log("Failed to clientSocket server.");
  62. socket.Close();
  63. break;
  64. }
  65. try
  66. {
  67. //接受数据保存至bytes当中
  68. byte[] bytes = new byte[4096];
  69. //Receive方法中会一直等待服务端回发消息
  70. //如果没有回发会一直在这里等着。
  71. int i = socket.Receive(bytes);
  72. if (i <= 0)
  73. {
  74. socket.Close();
  75. break;
  76. }
  77. Debug.Log(System.Text.Encoding.Default.GetString(bytes));
  78. }
  79. catch (Exception e)
  80. {
  81. Debug.Log("Failed to clientSocket error." + e);
  82. socket.Close();
  83. break;
  84. }
  85. }
  86. }
  87. //关闭Socket
  88. public void Closed()
  89. {
  90. if (socket != null && socket.Connected)
  91. {
  92. socket.Shutdown(SocketShutdown.Both);
  93. socket.Close();
  94. }
  95. socket = null;
  96. }
  97. //向服务端发送一条字符串
  98. //一般不会发送字符串 应该是发送数据包
  99. public void SendMessage(string str)
  100. {
  101. byte[] msg = Encoding.UTF8.GetBytes(str);
  102. if (!socket.Connected)
  103. {
  104. socket.Close();
  105. return;
  106. }
  107. try
  108. {
  109. IAsyncResult asyncSend = socket.BeginSend(msg, 0, msg.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
  110. bool success = asyncSend.AsyncWaitHandle.WaitOne(5000, true);
  111. if (!success)
  112. {
  113. socket.Close();
  114. Debug.Log("Failed to SendMessage server.");
  115. }
  116. }
  117. catch
  118. {
  119. Debug.Log("send message error");
  120. }
  121. }
  122. private void SendCallback(IAsyncResult asyncConnect)
  123. {
  124. Debug.Log("send success");
  125. }
  126. }

----------------------------------服务器-------------------------------------------------

  1. package org.u3d.server;
  2. import java.io.BufferedInputStream;
  3. import java.io.IOException;
  4. import java.net.ServerSocket;
  5. import java.net.Socket;
  6. /**
  7. *
  8. * unity3d 服务端
  9. *
  10. *
  11. *
  12. * @author lm
  13. *
  14. */
  15. public class U3dServer implements Runnable {
  16. public void run() {
  17. ServerSocket u3dServerSocket = null;
  18. while(true){
  19. try {
  20. u3dServerSocket=new ServerSocket(8000);
  21. System.out.println("u3d服务已经启动,监听8000端口");
  22. while (true) {
  23. Socket socket = u3dServerSocket.accept();
  24. System.out.println("客户端接入");
  25. new RequestReceiver(socket).start();
  26. }
  27. } catch (IOException e) {
  28. System.err.println("服务器接入失败");
  29. if (u3dServerSocket != null) {
  30. try {
  31. u3dServerSocket.close();
  32. } catch (IOException ioe) {
  33. }
  34. u3dServerSocket = null;
  35. }
  36. }
  37. // 服务延时重启
  38. try {
  39. Thread.sleep(5000);
  40. } catch (InterruptedException e) {
  41. }
  42. }
  43. }
  44. /**
  45. * 客户端请求接收线程
  46. * @author lm
  47. *
  48. */
  49. class RequestReceiver extends Thread {
  50. /** 报文长度字节数 */
  51. private int messageLengthBytes = 1024;
  52. private Socket socket;
  53. /** socket输入处理流 */
  54. private BufferedInputStream bis = null;
  55. public RequestReceiver(Socket socket) {
  56. this.socket = socket;
  57. }
  58. @Override
  59. public void run() {
  60. try {
  61. bis = new BufferedInputStream(socket.getInputStream());
  62. byte[] buf = new byte[messageLengthBytes];
  63. /**
  64. * 在Socket报文传输过程中,应该明确报文的域
  65. */
  66. while (true) {
  67. /*
  68. * 这种业务处理方式是根据不同的报文域,开启线程,采用不同的业务逻辑进行处理
  69. * 依据业务需求而定
  70. */
  71. //new RequestHandler(socket, buf).start();
  72. bis.read(buf);
  73. System.out.println(new String(buf,"utf-8"));
  74. Message msg=new GeneralMessage("i am server");
  75. msg.write(socket.getOutputStream());
  76. }
  77. } catch (IOException e) {
  78. System.err.println("读取报文出错");
  79. } finally {
  80. if (socket != null) {
  81. try {
  82. socket.close();
  83. } catch (IOException e) {
  84. }
  85. socket = null;
  86. }
  87. }
  88. }
  89. }
  90. /**
  91. * 描述: 请求处理器
  92. *
  93. */
  94. /* class RequestHandler extends Thread {
  95. }
  96. */
  97. }

  1. <pre name="code" class="java">public class U3dApplication {
  2. private static U3dApplication instance = null;
  3. private boolean stop;
  4. private U3dApplication() {
  5. }
  6. public static synchronized U3dApplication getApplication() {
  7. if (instance == null) {
  8. instance = new U3dApplication();
  9. }
  10. return instance;
  11. }
  12. public void start() {
  13. init();
  14. new Thread(new U3dServer(), "U3d Server").start();
  15. while (!stop) {
  16. try {
  17. Thread.sleep(1000);
  18. } catch (InterruptedException e) {
  19. }
  20. }
  21. }
  22. /**
  23. * @param args
  24. */
  25. public static void main(String[] args) {
  26. Runtime.getRuntime().addShutdownHook(new Thread() {
  27. @Override
  28. public void run() {
  29. getApplication().stopMe();
  30. }
  31. });
  32. getApplication().start();
  33. }
  34. public void stopMe() {
  35. System.out.println("系统即将关闭...");
  36. }
  37. /**
  38. * 初始化系统
  39. */
  40. private void init() {
  41. }
  42. }