GJM: Unity3D基于Socket通讯例子 [转载]

首先创建一个C# 控制台应用程序, 直接服务器端代码丢进去,然后再到Unity 里面建立一个工程,把客户端代码挂到相机上,运行服务端,再运行客户端。 高手勿喷!~!
完全源码已经奉上,大家开始研究吧!! 嘎嘎嘎!
服务端代码:Program.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net.Sockets;
- namespace SoketDemo
- {
- class Program
- {
- // 设置连接端口
- const int portNo = 500;
- static void Main(string[] args)
- {
- // 初始化服务器IP
- System.Net.IPAddress localAdd = System.Net.IPAddress.Parse("127.0.0.1");
- // 创建TCP侦听器
- TcpListener listener = new TcpListener(localAdd, portNo);
- listener.Start();
- // 显示服务器启动信息
- Console.WriteLine("Server is starting...n");
- // 循环接受客户端的连接请求
- while (true)
- {
- ChatClient user = new ChatClient(listener.AcceptTcpClient());
- // 显示连接客户端的IP与端口
- Console.WriteLine(user._clientIP + " is joined...n");
- }
- }
- }
- }
复制代码
服务端代码:ChatClient.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Collections;
- using System.Net.Sockets;
- namespace SoketDemo
- {
- class ChatClient
- {
- public static Hashtable ALLClients = new Hashtable(); // 客户列表
- private TcpClient _client; // 客户端实体
- public string _clientIP; // 客户端IP
- private string _clientNick; // 客户端昵称
- private byte[] data; // 消息数据
- private bool ReceiveNick = true;
- public ChatClient(TcpClient client)
- {
- this._client = client;
- this._clientIP = client.Client.RemoteEndPoint.ToString();
- // 把当前客户端实例添加到客户列表当中
- ALLClients.Add(this._clientIP, this);
- data = new byte[this._client.ReceiveBufferSize];
- // 从服务端获取消息
- client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
- }
- // 从客戶端获取消息
- public void ReceiveMessage(IAsyncResult ar)
- {
- int bytesRead;
- try
- {
- lock (this._client.GetStream())
- {
- bytesRead = this._client.GetStream().EndRead(ar);
- }
- if (bytesRead < 1)
- {
- ALLClients.Remove(this._clientIP);
- Broadcast(this._clientNick + " has left the chat");
- return;
- }
- else
- {
- string messageReceived = System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);
- if (ReceiveNick)
- {
- this._clientNick = messageReceived;
- Broadcast(this._clientNick + " has joined the chat.");
- //this.sendMessage("hello");
- ReceiveNick = false;
- }
- else
- {
- Broadcast(this._clientNick + ">" + messageReceived);
- }
- }
- lock (this._client.GetStream())
- {
- this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
- }
- }
- catch (Exception ex)
- {
- ALLClients.Remove(this._clientIP);
- Broadcast(this._clientNick + " has left the chat.");
- }
- }
- // 向客戶端发送消息
- public void sendMessage(string message)
- {
- try
- {
- System.Net.Sockets.NetworkStream ns;
- lock (this._client.GetStream())
- {
- ns = this._client.GetStream();
- }
- // 对信息进行编码
- byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(message);
- ns.Write(bytesToSend, 0, bytesToSend.Length);
- ns.Flush();
- }
- catch (Exception ex)
- {
- }
- }
- // 向客户端广播消息
- public void Broadcast(string message)
- {
- Console.WriteLine(message);
- foreach (DictionaryEntry c in ALLClients)
- {
- ((ChatClient)(c.Value)).sendMessage(message + Environment.NewLine);
- }
- }
- }
- }
复制代码
客户端代码 :ClientHandler
- using UnityEngine;
- using System.Collections;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Text;
- using System.Net.Sockets;
- public class ClientHandler : MonoBehaviour
- {
- const int portNo = 500;
- private TcpClient _client;
- byte[] data;
- public string nickName = "";
- public string message = "";
- public string sendMsg = "";
- void OnGUI()
- {
- nickName = GUI.TextField(new Rect(10, 10, 100, 20), nickName);
- message = GUI.TextArea(new Rect(10, 40, 300, 200), message);
- sendMsg = GUI.TextField(new Rect(10, 250, 210, 20), sendMsg);
- if (GUI.Button(new Rect(120, 10, 80, 20), "Connect"))
- {
- //Debug.Log("hello");
- this._client = new TcpClient();
- this._client.Connect("127.0.0.1", portNo);
- data = new byte[this._client.ReceiveBufferSize];
- //SendMessage(txtNick.Text);
- SendMessage(nickName);
- this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
- };
- if (GUI.Button(new Rect(230, 250, 80, 20), "Send"))
- {
- SendMessage(sendMsg);
- sendMsg = "";
- };
- }
- public void SendMessage(string message)
- {
- try
- {
- NetworkStream ns = this._client.GetStream();
- byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
- ns.Write(data, 0, data.Length);
- ns.Flush();
- }
- catch (Exception ex)
- {
- //MessageBox.Show(ex.ToString());
- }
- }
- public void ReceiveMessage(IAsyncResult ar)
- {
- try
- {
- int bytesRead;
- bytesRead = this._client.GetStream().EndRead(ar);
- if (bytesRead < 1)
- {
- return;
- }
- else
- {
- Debug.Log(System.Text.Encoding.ASCII.GetString(data, 0, bytesRead));
- message += System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);
- }
- this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
- }
- catch (Exception ex)
- {
- }
- }
- }
原 帖 地址 http://www.u3dchina.com/forum.php?mod=viewthread&tid=4741&extra=page%3D1%26filter%3Dsortid%26sortid%3D14%26sortid%3D14
如有版权问题 请联系我:993056011@qq.com
GJM: Unity3D基于Socket通讯例子 [转载]的更多相关文章
- Unity3d基于Socket通讯例子(转)
按语:按照下文,服务端利用网络测试工具,把下面客户端代码放到U3D中摄像机上,运行结果正确. http://www.manew.com/thread-102109-1-1.html 在一个网站上看到有 ...
- 基于Socket通讯(C#)和WebSocket协议(net)编写的两种聊天功能(文末附源码下载地址)
今天我们来盘一盘Socket通讯和WebSocket协议在即时通讯的小应用——聊天. 理论大家估计都知道得差不多了,小编也通过查阅各种资料对理论知识进行了充电,发现好多demo似懂非懂,拷贝回来又运行 ...
- 用Robot Framework+python来测试基于socket通讯的C/S系统(网络游戏)
项目终于换了方案,改用socket来实现而不是之前的http了,所以测试工具就不能用以前的了,因为测试人手少,逼不得已的必须要挖掘更多的自动化方案来弥补.于是先研究了下python的socket解决方 ...
- Unity3d网络游戏Socket通讯
http://blog.csdn.net/wu5101608/article/details/37999409
- php和c++socket通讯(基于字节流,二进制)
研究了一下PHP和C++socket通讯,用C++作为服务器端,php作为客户端进行. socket通讯是基于协议的,因此,只要双方协议一致就行. 关于协议的选择:我看过网上大部分协议都是在应用层的协 ...
- C#基于Socket的CS模式的完整例子
基于Socket服务器端实现本例主要是建立多客户端与服务器之间的数据传输,首先设计服务器.打开VS2008,在D:\C#\ch17目录下建立名为SocketServer的Windows应用程序.打开工 ...
- 闲来无事,写个基于TCP协议的Socket通讯Demo
.Net Socket通讯可以使用Socket类,也可以使用 TcpClient. TcpListener 和 UdpClient类.我这里使用的是Socket类,Tcp协议. 程序很简单,一个命令行 ...
- Android 基于Socket的聊天应用(二)
很久没写BLOG了,之前在写Android聊天室的时候答应过要写一个客户(好友)之间的聊天demo,Android 基于Socket的聊天室已经实现了通过Socket广播形式的通信功能. 以下是我写的 ...
- 高性能、高可用性Socket通讯库介绍 - 采用完成端口、历时多年调优!(附文件传输程序)
前言 本人从事编程开发十余年,因为工作关系,很早就接触socket通讯编程.常言道:人在压力下,才可能出非凡的成果.我从事的几个项目都涉及到通讯,为我研究通讯提供了平台,也带来了动力.处理socket ...
随机推荐
- asp.net/html清理页面缓存的方法
(1) MVC BaseController: Controller内 protected override void Initialize(System.Web.Routing.RequestC ...
- XML学习笔记1——概述
我对于XML是很不够重视的,认识也是非常肤浅的,因为在之前的Web经验中,基本上都可以使用JSON来代替XML,JSON网络流量少,解析快,JS支持好等这些特点让我对自己的观点坚信不疑.然而我渐渐地改 ...
- Python流程控制语句
人们常说人生就是一个不断做选择题的过程:有的人没得选,只有一条路能走:有的人好一点,可以二选一:有些能力好或者家境好的人,可以有更多的选择:还有一些人在人生的迷茫期会在原地打转,找不到方向.对于相信有 ...
- ssh(sturts2_spring_hibernate) 框架搭建之JPA代替hibernate
一.JPA用来替代hibernate ⒈JPA的全称是JAVA Persistence API.指的是JPA通过注解或者是XML描述对象—关系表的映射关系,并且将运行的实体对象持久化数据库中. ⒉JP ...
- Android开发之时间日期2
昨天给大家分享了一个时间和日期设置的小例子,今天发现Android的布局组件中有关于时间和日期的设置的组件,废话不多说,先给大家分享一下我的经验. 时间日期设置组件:TimePicker.DatePi ...
- 《BI那点儿事》数据挖掘初探
什么是数据挖掘? 数据挖掘(Data Mining),又称信息发掘(Knowledge Discovery),是用自动或半自动化的方法在数据中找到潜在的,有价值的信息和规则. 数据挖掘技术来源于数据库 ...
- Prim算法(一)之 C语言详解
本章介绍普里姆算法.和以往一样,本文会先对普里姆算法的理论论知识进行介绍,然后给出C语言的实现.后续再分别给出C++和Java版本的实现. 目录 1. 普里姆算法介绍 2. 普里姆算法图解 3. 普里 ...
- MongoDB的学习--聚合
最近要去的新项目使用mysql,趁着还没忘记,总结记录以下MongoDB的聚合. 聚合是泛指各种可以处理批量记录并返回计算结果的操作.MongoDB提供了丰富的聚合操作,用于对数据集执行计算操作.在 ...
- Spring MVC 学习总结(五)——校验与文件上传
Spring MVC不仅是在架构上改变了项目,使代码变得可复用.可维护与可扩展,其实在功能上也加强了不少. 验证与文件上传是许多项目中不可缺少的一部分.在项目中验证非常重要,首先是安全性考虑,如防止注 ...
- .NET知识结构
.NET知识结构 .NET介绍 微软.NET战略及技术体系,.NET Framework框架类库(FCL),公共语言运行时(CLR),通用类型系统(CTS),公共语言规范(CLS),程序集(Assem ...