码迷,mamicode.com
首页 > 编程语言 > 详细

Unity C# Scoket Thread

时间:2019-05-19 11:57:03      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:gen   listening   star   data   stc   mode   关于   程序   close   

关于 Scoket和Thread 也没什么要说的,网上有很多资料。但是需要注意的是 Scoket和Thread 都需要创建和杀死。不然一定会造成程序假死。好了上代码

服务器:

技术图片
  1 using System;
  2 using System.Collections;
  3 using System.Collections.Generic;
  4 using System.IO;
  5 using System.Net;
  6 using System.Net.Sockets;
  7 using System.Text;
  8 using System.Threading;
  9 using UnityEngine;
 10 
 11 public class TCPTestServer : MonoBehaviour
 12 {
 13     #region private members     
 14     /// <summary>     
 15     /// 服务器监听连接    
 16     /// </summary>     
 17     private TcpListener tcpListener;
 18     /// <summary> 
 19     /// 服务器监听线程
 20     /// </summary>     
 21     private Thread tcpListenerThread;
 22     /// <summary>     
 23     /// 创建连接上的客户端
 24     /// </summary>     
 25     private TcpClient connectedTcpClient;
 26     #endregion
 27 
 28     // Use this for initialization
 29     void Start()
 30     {
 31         // 启动服务器监听线程        
 32         tcpListenerThread = new Thread(new ThreadStart(ListenForIncommingRequests));
 33         tcpListenerThread.IsBackground = true;
 34         tcpListenerThread.Start();
 35     }
 36 
 37     // Update is called once per frame
 38     void Update()
 39     {
 40         // 服务器发送测试数据
 41         if (Input.GetKeyDown(KeyCode.R))
 42         {
 43             Debug.Log("R");
 44             SendMessage();
 45         }
 46 
 47         if (Input.GetKeyDown(KeyCode.Escape))
 48         {
 49             Debug.Log("Escape Server");
 50             Close();
 51             Application.Quit();
 52         }
 53     }
 54 
 55     /// <summary>     
 56     /// 服务器监听
 57     /// </summary>     
 58     private void ListenForIncommingRequests()
 59     {
 60         try
 61         {
 62             // 创建监听端口
 63             tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8052);
 64             tcpListener.Start();
 65             Debug.Log("Server is listening");
 66             Byte[] bytes = new Byte[1024];
 67             while (true)
 68             {
 69                 using (connectedTcpClient = tcpListener.AcceptTcpClient())
 70                 {                
 71                     using (NetworkStream stream = connectedTcpClient.GetStream())
 72                     {
 73                         int length;                        
 74                         while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
 75                         {
 76                             var incommingData = new byte[length];
 77                             Array.Copy(bytes, 0, incommingData, 0, length);                            
 78                             string clientMessage = Encoding.Unicode.GetString(incommingData);
 79                             Debug.Log("客户端: " + clientMessage);
 80                         }
 81                     }
 82                 }
 83             }
 84         }
 85         catch (SocketException socketException)
 86         {
 87             Debug.Log("SocketException " + socketException.ToString());
 88         }
 89     }
 90     /// <summary>     
 91     /// Send message to client using socket connection.     
 92     /// </summary>     
 93     private void SendMessage()
 94     {
 95         if (connectedTcpClient == null)
 96         {
 97             return;
 98         }
 99 
100         try
101         {
102             // Get a stream object for writing.             
103             NetworkStream stream = connectedTcpClient.GetStream();
104             if (stream.CanWrite)
105             {
106                 string serverMessage = "小畜生";
107                 byte[] serverMessageAsByteArray = Encoding.Unicode.GetBytes(serverMessage);
108                 stream.Write(serverMessageAsByteArray, 0, serverMessageAsByteArray.Length);
109             }
110         }
111         catch (SocketException socketException)
112         {
113             Debug.Log("Socket exception: " + socketException);
114         }
115     }
116 
117     private void OnApplicationQuit()
118     {
119         Close();
120     }
121 
122     private void OnDestroy()
123     {
124         Close();
125     }
126 
127     // 关闭TCP连接和线程,防止程序假死
128     void Close()
129     {
130         if (tcpListenerThread != null)
131         {
132             tcpListenerThread.Interrupt();
133             tcpListenerThread.Abort();
134         }
135 
136         if(null != tcpListener)
137         {
138             tcpListener.Stop();
139         }
140 
141         if(null != connectedTcpClient)
142         {
143             connectedTcpClient.Close();
144         }
145     }
146 }
Server

客户端:

技术图片
  1 using System;
  2 using System.Collections;
  3 using System.Collections.Generic;
  4 using System.Net.Sockets;
  5 using System.Text;
  6 using System.Threading;
  7 using UnityEngine;
  8 using UnityEngine.UI;
  9 using Newtonsoft.Json;
 10 using System.IO;
 11 
 12 public class TCPTestClient : MonoBehaviour
 13 {
 14     #region private members     
 15     private TcpClient socketConnection;
 16     private Thread clientReceiveThread;
 17     #endregion
 18     // Use this for initialization     
 19     void Start()
 20     {
 21         
 22     }
 23     // Update is called once per frame
 24     void Update()
 25     {
 26         // 连接服务器
 27         if (Input.GetKeyDown(KeyCode.Q))
 28         {
 29             Debug.Log("Q");
 30             ConnectToTcpServer();
 31         }
 32 
 33         // 发送消息到服务器
 34         if (Input.GetKeyDown(KeyCode.Space))
 35         {
 36             Debug.Log("Space");
 37             SendMessage();
 38         }
 39 
 40         if (Input.GetKeyDown(KeyCode.Escape))
 41         {
 42             Debug.Log("Escape Client");
 43             Close();
 44             Application.Quit();
 45         }
 46 
 47     }
 48     /// <summary>     
 49     /// 连接服务器    
 50     /// </summary>     
 51     private void ConnectToTcpServer()
 52     {
 53         try
 54         {
 55             clientReceiveThread = new Thread(new ThreadStart(ListenForData));
 56             clientReceiveThread.IsBackground = true;
 57             clientReceiveThread.Start();
 58         }
 59         catch (Exception e)
 60         {
 61             Debug.Log("On client connect exception " + e);
 62         }
 63     }
 64     /// <summary>     
 65     /// 接受服务器消息
 66     /// </summary>     
 67     private void ListenForData()
 68     {
 69         try
 70         {
 71             socketConnection = new TcpClient("localhost", 8052);
 72             Byte[] bytes = new Byte[1024];
 73             while (true)
 74             {
 75                 // Using 用完就会销毁            
 76                 using (NetworkStream stream = socketConnection.GetStream())
 77                 {
 78                     int length;
 79                     while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
 80                     {
 81                         var incommingData = new byte[length];
 82                         Array.Copy(bytes, 0, incommingData, 0, length);
 83                         string serverMessage = Encoding.Unicode.GetString(incommingData);
 84                         Debug.Log("服务器: " + serverMessage);                                  
 85                     }
 86                 }
 87             }
 88         }
 89         catch (SocketException socketException)
 90         {
 91             Debug.Log("Socket exception: " + socketException);
 92         }
 93     }
 94     /// <summary>     
 95     /// 发送数据    
 96     /// </summary>     
 97     private void SendMessage()
 98     {
 99         if (socketConnection == null)
100         {
101             return;
102         }
103         try
104         {        
105             NetworkStream stream = socketConnection.GetStream();
106             if (stream.CanWrite)
107             {
108                 string clientMessage = "小妖精";
109                 byte[] clientMessageAsByteArray = Encoding.Unicode.GetBytes(clientMessage);
110                 stream.Write(clientMessageAsByteArray, 0, clientMessageAsByteArray.Length);
111             }
112         }
113         catch (SocketException socketException)
114         {
115             Debug.Log("Socket exception: " + socketException);
116         }
117     }
118 
119     public void CreatePagoda(string str)
120     {
121         ModelCreate.modelDelegate(str);
122     }
123 
124     private void OnApplicationQuit()
125     {
126         Close();
127     }
128 
129     private void OnDestroy()
130     {
131         Close();
132     }
133 
134     // 关闭TCP连接和线程,防止程序假死
135     void Close()
136     {
137         if (null != clientReceiveThread)
138         {
139             clientReceiveThread.Interrupt();
140             clientReceiveThread.Abort();            
141         }
142         if (null != socketConnection)
143         {
144             socketConnection.Close();
145         }
146     }
147 }
Client

 

Unity C# Scoket Thread

标签:gen   listening   star   data   stc   mode   关于   程序   close   

原文地址:https://www.cnblogs.com/huojiaoqingchun0123/p/10888532.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!