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 ...
随机推荐
- JVM相关面试题
1.JVM 基本机构 1.1 类加载子系统负责从文件系统或者网络中加载Class信息,加载的类信息存放于一块称为方法区的内存空间.除了类的信息外,方法区中可能还会存放运行时常量池信息,包括字符串字面量 ...
- python之time模块和hashlib模块
一.time模块 import time print(time.strftime('%Y-%m-%d %H:%M:%S'))#获取当前的格式化时间,time.strftime(format) prin ...
- signal——信号集
1.信号集 每个进程都有一个信号屏蔽字,它规定了当前要阻塞递送到该进程的信号集.对于每种可能的信号,该屏蔽字中都有一bit位与之对应.信号数可能会超过一个整型数所包含的二进制位数,因此POSIX.1 ...
- 通俗易懂JSONP讲解
原文地址:http://www.cnblogs.com/dowinning/archive/2012/04/19/json-jsonp-jquery.html JSON的格式或者叫规则: JSON能够 ...
- 因为AI,所以爱
作为技术驱动型公司 自我颠覆的核心就是技术上有所突破 2019技术奇点大会上,创始人行在提出 「未来,大数据和人工智能 将成为商业升级的智能发动机」 这与我们的使命不谋而合 时间退回到2016年的冬天 ...
- 1076 Wifi密码 (15 分)
题目:传送门 下面是微博上流传的一张照片:“各位亲爱的同学们,鉴于大家有时需要使用 wifi,又怕耽误亲们的学习,现将 wifi 密码设置为下列数学题答案:A-1:B-2:C-3:D-4:请同学们自己 ...
- 18)添加引号转移函数,防止SQL注入
目录机构: 然后我的改动代码: MysqlDB.class.php <?php /** * Created by PhpStorm. * User: Interact * Date: 2017/ ...
- pycharm中无法调用pip的安装包
https://blog.csdn.net/sinat_23619409/article/details/79962518 较详细:https://blog.csdn.net/weixin_41287 ...
- Java包装类之实体类不要使用基本类型
[color=rgba(0, 0, 0, 0.75)]今天来记录一下,在项目中因为基本类型,所产生的bug.**U•ェ•*U** 包装类:8种基本类型的包装类 应用场景:数据库建立实体映射多用包装类 ...
- freeRadius日志关闭
vim /etc/raddb/radiusd.conf #file = ${logdir}/radius.log file = /dev/null vim /etc/raddb/modules/det ...