untiy3d-socket简单应用
2016-09-30 09:53
423 查看
本文固定链接: http://blog.csdn.net/u013108312/article/details/52709089
转载请注明: CircleGood 2016年09月30日 于 CircleGood程序 发表
服务端:
vs 控制台应用程序,
客户端Unity3d:
本文固定链接: http://blog.csdn.net/u013108312/article/details/52709089
转载请注明: CircleGood 2016年09月30日 于 CircleGood程序 发表
转载请注明: CircleGood 2016年09月30日 于 CircleGood程序 发表
服务端:
vs 控制台应用程序,
static void Main(string[] args) { //1.创建一个socket对象 Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//寻址方案,套接字类型,协议类型 //2.绑定一个ip和端口 //IPAddress ipaddress = new IPAddress(new byte[] { 127, 0, 0, 1 }); IPAddress ipaddress = IPAddress.Parse("127.0.0.1");//将一个字符串类型的ip地址转化成一个IPAddress的对象 EndPoint endpoint = new IPEndPoint(ipaddress, 5000); tcpServer.Bind(endpoint);//向操作系统申请一个可用的ip和端口号用来通讯 //3.开始监听客户端的连接请求 tcpServer.Listen(100); Console.WriteLine("服务器启动完成"); Socket clientSocket = tcpServer.Accept();//暂停当期线程,直到一个客户端连接过来 Console.WriteLine("接收到客户端的连接请求!"); //4.发送/接受消息 string message = "Hello Client"; var data = Encoding.UTF8.GetBytes(message); //将字符串转化成字节数组 clientSocket.Send(data); Console.WriteLine("服务器向客户端发送了一条消息:" + message); //接受客户端消息 byte[] data2 = new byte[1024]; //存放消息的字节数组容器 int length = clientSocket.Receive(data2); string message2 = Encoding.UTF8.GetString(data2, 0, length); //bytes转化成string Console.WriteLine("服务器接收到客户端发送过来的消息:" + message2); Console.Read(); } }
客户端Unity3d:
using UnityEngine; using System.Collections; using System.Net.Sockets; using System.Net; using System.Text; public class SocketClient : MonoBehaviour { private Socket tcpClient; private string serverIP = "127.0.0.1"; private int serverPort = 5000; void Start() { //1.创建一个socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //2.建立连接请求 IPAddress ipaddress = IPAddress.Parse(serverIP); EndPoint endpoint = new IPEndPoint(ipaddress, serverPort); tcpClient.Connect(endpoint); Debug.Log("请求服务器连接"); //3.接受/发送消息 byte[] data = new byte[1024]; int length = tcpClient.Receive(data); var message = Encoding.UTF8.GetString(data, 0, length); Debug.Log("客户端接收到服务器发来的消息:" + message); //发送消息 string message2 = "Client Say To Server Hello"; tcpClient.Send(Encoding.UTF8.GetBytes(message2)); Debug.Log("客户端向服务器发送消息:" + message2); } }
本文固定链接: http://blog.csdn.net/u013108312/article/details/52709089
转载请注明: CircleGood 2016年09月30日 于 CircleGood程序 发表
相关文章推荐
- Android缓存机制介绍:一个缓存框架推荐
- mybatis动态sql中的trim标签的使用
- C#提示框代码
- 并发新特性—阻塞队列与阻塞栈
- 【整理】1到n的数字典序排序(N为long long)
- 计算两个日期之间的工作日(去掉周末和节假日)
- 分布式事务——使用消息队列消除两阶段提交
- centos6.5 安装linux 环境
- USB枚举详细过程剖析(转)
- iOS移动开发周报-第24期
- 对话框自带滚动条的使用
- C#线程类Thread初步
- 支付宝接入
- 关于HTTP请求出现 405状态码 not allowed的解决办法
- Openstack 之 ceilometer: Alarm
- Maintaining Consumer Groups, Plans, and Directives
- Bootstrap progress-bar
- Leetcode-12. Integer to Roman
- 出售时间的三条铁律
- iOS移动开发周报-第23期