Unity3d简单的socket通信

vs2010或其他创建C#工程
C#端代码一:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets; namespace SoketDemo
{
class Program
{
// 设置连接端口
const int portNo = ; 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");
}
}
}
代码二:
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);
}
} }
}
unity端代码,直接挂载到摄像头:
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 = ;
private TcpClient _client;
byte[] data; public string nickName = "";
public string message = "";
public string sendMsg = ""; void OnGUI()
{
nickName = GUI.TextField(new Rect(, , , ), nickName);
message = GUI.TextArea(new Rect(, , , ), message);
sendMsg = GUI.TextField(new Rect(, , , ), sendMsg); if (GUI.Button(new Rect(, , , ), "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, , System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
}; if (GUI.Button(new Rect(, , , ), "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, , 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 < )
{
return;
}
else
{ Debug.Log(System.Text.Encoding.ASCII.GetString(data, , bytesRead)); message += System.Text.Encoding.ASCII.GetString(data, , bytesRead);
} this._client.GetStream().BeginRead(data, , System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null); }
catch (Exception ex)
{ }
}
}
这样就得了。
Unity3d简单的socket通信的更多相关文章
- php简单实现socket通信
socket通信的原理在这里就不说了,它的用途还是比较广泛的,我们可以使用socket来做一个API接口出来,也可以使用socket来实现两个程序之间的通信,我们来研究一下在php里面如何实现sock ...
- Linux下简单的socket通信实例
Linux下简单的socket通信实例 If you spend too much time thinking about a thing, you’ll never get it done. —Br ...
- Android简单实现Socket通信,client连接server后,server向client发送文字数据
案例实现的是简单的Socket通信,当client(Androidclient)连接到指定server以后,server向client发送一句话文字信息(你能够拓展其他的了) 先看一下服务端程序的实现 ...
- 简单的Socket通信
Socket简介 Socket又称"套接字",应用程序通常通过"套接字"向网络发出请求或者应答网络请求. 服务端步骤: • socket:创建服务器socket ...
- Day 6-2简单的socket通信
什么是socket? Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口.在设计模式中,Socket其实就是一个门面模式,它把复杂的TCP/IP协议族隐藏在Socket接口后面 ...
- Java实现简单的socket通信
今天学习了一下java如何实现socket通信,感觉难点反而是在io上,因为java对socket封装已经很完善了. 今天代码花了整个晚上调试,主要原因是io的flush问题和命令行下如何运行具有pa ...
- C#版 Socket编程(最简单的Socket通信功能)
示例程序是同步套接字程序,功能很简单,只是客户端发给服务器一条信息,服务器向客户端返回一条信息:这里只是一个简单的示例,是一个最基本的socket编程流程,在接下来的文章中,会依次记录套接字的同步和异 ...
- Java 实现简单的 Socket 通信
Java socket 封装了传输层的实现细节,开发人员可以基于 socket 实现应用层.本文介绍了 Java socket 简单用法. 1. 传输层协议 传输层包含了两种协议,分别是 TCP (T ...
- 简单的Socket通信(简单的在线聊天)---winform
注:本博客适合刚开始学习winform程序的初学者,大牛请绕道(跪求大牛指导文中不足) .....10w字废话自动省略,直接开始正题. 首先从最基本的建立winform开始(本项目用的Vs2017) ...
随机推荐
- 磁盘IO:缓存IO与直接IO
文件系统IO分为DirectIO和BufferIO,其中BufferIO也叫Normal IO. 1. 缓存IO 缓存I/O又被称作标准I/O,大多数文件系统的默认I/O操作都是缓存I/O.在Linu ...
- J2EE struts2MVC应用在线书签1
序:之前花了一天研究了一下filter,虽然是实现了MVC模式开发了 WebBookmark,但是代码过于冗长,集中在filter中使用if语句不易阅读,为了体现两份作业的不同点,我决定学习 Java ...
- VMWare下ubuntu无法全屏的问题解决
遇到的情况: 在VMWare中,安装ubuntu 最新版操作系统(16.04).运行该系统,发现ubuntu系统在虚拟机中,只能居中显示,全屏也只能占一半显示屏幕.怎么看,怎么不舒服. 分析问题: 一 ...
- 使用react native制作的微博客户端
简要说明: 因为微博授权权限设置,本人的微博开放者账号权限太低,如果出现 'api请求次数受限,请更换. 10023' 弹框 或者 授权界面出错,需要自行更换开放者应用的appkey,授权回调页,Ap ...
- lightoj1336数论基础
#include<iostream> #include<cstdio> #include<cmath> #define ll long long using nam ...
- poj 1001 分析
1) n = 0; return 1: 2) n = 1; bool standardizeNumNoDot(string &s){标准化是一定要得} _将‘.’前后的〇全部去除,正常retu ...
- 工具类总结---(六)---之http及https请求
下面使用的是HttpURLConnection进行的网络链接,并对https进行了忽略证书. 在这个utils里面,也使用到前面几个utils,比如下载文件的方法,就使用到了Fileutils pac ...
- hdu1011 Starship Troopers 树形DP
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1011 思路:很明显的树形背包 定义dp[root][m]表示以root为根,派m个士兵的最优解,那么d ...
- [刷题]Codeforces 785D - Anton and School - 2
Description As you probably know, Anton goes to school. One of the school subjects that Anton studie ...
- [笔记]cin、cout与scanf、printf的效率差异对比分析
之前上传UVa227 puzzle时,好不容易AC了,但发现自己用时50(ms),而在VJ上看到人家都是40ms.20ms,于是打开一个20ms的代码查看人家强在哪里.但结果研究了半天感觉差不多,于是 ...