Unity C# Scoket Thread
关于 Scoket和Thread 也没什么要说的,网上有很多资料。但是需要注意的是 Scoket和Thread 都需要创建和杀死。不然一定会造成程序假死。好了上代码
服务器:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine; public class TCPTestServer : MonoBehaviour
{
#region private members
/// <summary>
/// 服务器监听连接
/// </summary>
private TcpListener tcpListener;
/// <summary>
/// 服务器监听线程
/// </summary>
private Thread tcpListenerThread;
/// <summary>
/// 创建连接上的客户端
/// </summary>
private TcpClient connectedTcpClient;
#endregion // Use this for initialization
void Start()
{
// 启动服务器监听线程
tcpListenerThread = new Thread(new ThreadStart(ListenForIncommingRequests));
tcpListenerThread.IsBackground = true;
tcpListenerThread.Start();
} // Update is called once per frame
void Update()
{
// 服务器发送测试数据
if (Input.GetKeyDown(KeyCode.R))
{
Debug.Log("R");
SendMessage();
} if (Input.GetKeyDown(KeyCode.Escape))
{
Debug.Log("Escape Server");
Close();
Application.Quit();
}
} /// <summary>
/// 服务器监听
/// </summary>
private void ListenForIncommingRequests()
{
try
{
// 创建监听端口
tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), );
tcpListener.Start();
Debug.Log("Server is listening");
Byte[] bytes = new Byte[];
while (true)
{
using (connectedTcpClient = tcpListener.AcceptTcpClient())
{
using (NetworkStream stream = connectedTcpClient.GetStream())
{
int length;
while ((length = stream.Read(bytes, , bytes.Length)) != )
{
var incommingData = new byte[length];
Array.Copy(bytes, , incommingData, , length);
string clientMessage = Encoding.Unicode.GetString(incommingData);
Debug.Log("客户端: " + clientMessage);
}
}
}
}
}
catch (SocketException socketException)
{
Debug.Log("SocketException " + socketException.ToString());
}
}
/// <summary>
/// Send message to client using socket connection.
/// </summary>
private void SendMessage()
{
if (connectedTcpClient == null)
{
return;
} try
{
// Get a stream object for writing.
NetworkStream stream = connectedTcpClient.GetStream();
if (stream.CanWrite)
{
string serverMessage = "小畜生";
byte[] serverMessageAsByteArray = Encoding.Unicode.GetBytes(serverMessage);
stream.Write(serverMessageAsByteArray, , serverMessageAsByteArray.Length);
}
}
catch (SocketException socketException)
{
Debug.Log("Socket exception: " + socketException);
}
} private void OnApplicationQuit()
{
Close();
} private void OnDestroy()
{
Close();
} // 关闭TCP连接和线程,防止程序假死
void Close()
{
if (tcpListenerThread != null)
{
tcpListenerThread.Interrupt();
tcpListenerThread.Abort();
} if(null != tcpListener)
{
tcpListener.Stop();
} if(null != connectedTcpClient)
{
connectedTcpClient.Close();
}
}
}
Server
客户端:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
using Newtonsoft.Json;
using System.IO; public class TCPTestClient : MonoBehaviour
{
#region private members
private TcpClient socketConnection;
private Thread clientReceiveThread;
#endregion
// Use this for initialization
void Start()
{ }
// Update is called once per frame
void Update()
{
// 连接服务器
if (Input.GetKeyDown(KeyCode.Q))
{
Debug.Log("Q");
ConnectToTcpServer();
} // 发送消息到服务器
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Space");
SendMessage();
} if (Input.GetKeyDown(KeyCode.Escape))
{
Debug.Log("Escape Client");
Close();
Application.Quit();
} }
/// <summary>
/// 连接服务器
/// </summary>
private void ConnectToTcpServer()
{
try
{
clientReceiveThread = new Thread(new ThreadStart(ListenForData));
clientReceiveThread.IsBackground = true;
clientReceiveThread.Start();
}
catch (Exception e)
{
Debug.Log("On client connect exception " + e);
}
}
/// <summary>
/// 接受服务器消息
/// </summary>
private void ListenForData()
{
try
{
socketConnection = new TcpClient("localhost", );
Byte[] bytes = new Byte[];
while (true)
{
// Using 用完就会销毁
using (NetworkStream stream = socketConnection.GetStream())
{
int length;
while ((length = stream.Read(bytes, , bytes.Length)) != )
{
var incommingData = new byte[length];
Array.Copy(bytes, , incommingData, , length);
string serverMessage = Encoding.Unicode.GetString(incommingData);
Debug.Log("服务器: " + serverMessage);
}
}
}
}
catch (SocketException socketException)
{
Debug.Log("Socket exception: " + socketException);
}
}
/// <summary>
/// 发送数据
/// </summary>
private void SendMessage()
{
if (socketConnection == null)
{
return;
}
try
{
NetworkStream stream = socketConnection.GetStream();
if (stream.CanWrite)
{
string clientMessage = "小妖精";
byte[] clientMessageAsByteArray = Encoding.Unicode.GetBytes(clientMessage);
stream.Write(clientMessageAsByteArray, , clientMessageAsByteArray.Length);
}
}
catch (SocketException socketException)
{
Debug.Log("Socket exception: " + socketException);
}
} public void CreatePagoda(string str)
{
ModelCreate.modelDelegate(str);
} private void OnApplicationQuit()
{
Close();
} private void OnDestroy()
{
Close();
} // 关闭TCP连接和线程,防止程序假死
void Close()
{
if (null != clientReceiveThread)
{
clientReceiveThread.Interrupt();
clientReceiveThread.Abort();
}
if (null != socketConnection)
{
socketConnection.Close();
}
}
}
Client
Unity C# Scoket Thread的更多相关文章
- Unity多线程(Thread)和主线程(MainThread)交互使用类——Loom工具分享
Unity多线程(Thread)和主线程(MainThread)交互使用类——Loom工具分享 By D.S.Qiu 尊重他人的劳动,支持原创,转载请注明出处:http.dsqiu.iteye.com ...
- 结合Thread Ninja明确与处理异步协程中的异常
Thread Ninja说明: Thread Ninja - Multithread Coroutine Requires Unity 3.4.0 or higher. A simple script ...
- Loom工具使用分享
Unity多线程(Thread)和主线程(MainThread)交互使用类——Loom工具分享 时间 2014-03-09 11:04:04 ITeye-博客 原文 http://dsqiu.it ...
- Unity Get Thread Content Failed
最近在使用Unity做项目时,发现总是莫名的出现“Get Thread Content Failed”的消息弹出,然后Unity就卡死了,这样反反复复,后来查到是因为一些杀毒软件在阻止Unity,尝试 ...
- Unity使用C#实现简单Scoket连接及服务端与客户端通讯
简介: 网络编程是个很有意思的事情,偶然翻出来很久之前刚开始看Socket的时候写的一个实例,贴出来吧 Unity中实现简单的Socket连接,c#中提供了丰富的API,直接上代码. 服务端代码: [ ...
- C#之实现Scoket心跳机制
C#之实现Scoket心跳机制 标签: UnityC#TCPSocket心跳 2017-05-17 09:58 1716人阅读 评论(0) 收藏 举报 分类: Unity(134) C#(6) ...
- 《Unity 3D游戏客户端基础框架》多线程异步 Socket 框架构建
引言: 之前写过一个 demo 案例大致讲解了 Socket 通信的过程,并和自建的服务器完成连接和简单的数据通信,详细的内容可以查看 Unity3D -- Socket通信(C#).但是在实际项目应 ...
- Unity性能优化(4)-官方教程Optimizing graphics rendering in Unity games翻译
本文是Unity官方教程,性能优化系列的第四篇<Optimizing graphics rendering in Unity games>的翻译. 相关文章: Unity性能优化(1)-官 ...
- Unity游戏开发中的内存管理_资料
内存是手游的硬伤——Unity游戏Mono内存管理及泄漏http://wetest.qq.com/lab/view/135.html 深入浅出再谈Unity内存泄漏http://wetest.qq.c ...
随机推荐
- 倾斜摄影数据转cesium 3D tiles工具介绍
软件操作:http://jingyan.baidu.com/article/3aed632e3912c8701080912c.html 软件测试数据: 数据,油库链接: http://pan.baid ...
- Qt error C2338: No Q_OBJECT in the class with the signal错误解决办法(无法编译过信号与槽)
由于没有继承QObject类而引起的 只需继承QObject类即可 如果已经继承了QObject类,编译还出现错误 将QObject类放在最前面继承:public QObject 最后即可编译通过
- Sampling Error|Sampling mean|population mean
7.1 Sampling Error; the Need for Sampling Distributions 样本均值的三种表达: Sampling distribution of the samp ...
- 让一个div拖动和让一个panel拖动加拉大拉小
一.让一个div拖动 <!doctype html> <html xmlns="http://www.w3.org/1999/xhtml"> <hea ...
- mpvue框架的小程序和H5同时开发
demo链接1.样式统一为了达到共用一套样式,采用px2rem-loader和px2rpx-loader进行代码的打包,细节如下: 由于UI设计图是在蓝湖上标注,宽度750,选择像素 PX 样式中直接 ...
- verilog的function使用
语法: function [range] function_id; input_declaration other_declarations procedural_statement ...
- C# Dictionary字典类介绍
说明 必须包含名空间System.Collection.Generic Dictionary里面的每一个元素都是一个键值对(由二个元素组成:键和值) 键必须是唯一的,而值不需要唯 ...
- when|nobody|hazard|lane|circuit|
How can I help them they won't listen to me? 题目解析 考查从句.此句意为:如果他们要是不听我的话,我怎么帮助他们?此处,when引导的状语从句表示假设事 ...
- 吴裕雄--天生自然HTML学习笔记:HTML 基础- 4个实例
HTML 标题 HTML 标题(Heading)是通过<h1> - <h6> 标签来定义的. 实例 <h1>这是一个标题</h1> <h2> ...
- JAVAscript的DOM操作及实例
一.Windows对象操作 (1)用代码打开窗口:window.open("第一部分","第二部分","第三部分","第四部分&q ...