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 ...
随机推荐
- python调用存储过程失败返回1787错误
(1787, 'When @@GLOBAL.ENFORCE_GTID_CONSISTENCY = 1, the statements CREATE TEMPORARY TABLE and DROP T ...
- spring boot 配置文件properties和YAML详解
spring boot 配置文件properties和YAML详解 properties中配置信息并获取值. 1:在application.properties配置文件中添加: 根据提示创建直接创建. ...
- SCI|EI|ISTP|万方|istic|NSTL|CASTD|CNKI|nlc|ethesys|CALIS|CETD|proquest|NDLTD|中国科学院学位论文检索系统|学位论文
BD AC D 三大检索指的是:SCI(科学引文索引 ).EI(工程索引 ).ISTP(科技会议录索引 ) 即Science Citation Index.Engineering Index.Conf ...
- python函数参数理解
1.位置参数 函数调用时,参数赋值按照位置顺序依次赋值. e.g. def function(x): 3 return x * x 5 print function(2) 输出结果: 4 def fu ...
- Qt QByteArray 与 char* 的转换
QByteArray 转换为 char * char *ch;//不要定义成ch[n]; QByteArray byte; ch = byte.data(); char * 转换为 QByteArra ...
- python中coding:utf-8的作用
或者
- 在 mac osx 上安装OpenOffice并以服务的方式启动
OpenOffice是Apache基金会旗下的一款先进的开源办公软件套件,包含文本文档.电子表格.演示文稿.绘图.数据库等.包含Microsoft office所有功能.它不仅可以作为桌面应用供普通用 ...
- 吴裕雄--天生自然KITTEN编程:角色移动
- Thrift RPC实战(三) thrift序列化揭秘
本文主要讲解Thrift的序列化机制, 看看thrift作为数据交换格式是如何工作的? 1.构造应用场景: 1). 首先我们先来定义下thrift的简单结构. 1 2 3 4 5 namespace ...
- requests库入门-16-Session和Cookie
分类专栏: Python接口自动化测试之requests库入门 作者 | Anthony_tester ,300w+访问量博主,Oracle测试开发工程师. 地址 | https://blog.csd ...