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) ...
随机推荐
- 系统启动 之 Linux系统启动概述(2)
博客:http://blog.csdn.net/younger_china/article/details/51615916 Linu系统启动是一个"冗长乏味"的过程,那么我们现就 ...
- SOA 下实现分布式 调用 cxf+ webService +动态调用
近期项目间隙 自学了 webservice 一下 是我写的 一个demo 首先我们在web.xml 里配置如下 <servlet> <servlet-name>CXFS ...
- F# 之旅(上)
写在前面的话 解答一下在上一篇文章<在Visual Studio中入门F#>中有人的提问, 1. 问:是准备写 F# 系列吗? 答:当然不是,本人也是刚刚学习 F#,只是翻译微软官方 ...
- 对象克隆(clone)实例详解
<?php class Staff { public $name; public $age; public $salary; public function __construct($name, ...
- CSS完美实现iframe高度自适应(支持跨域)
Iframe的强大功能偶就不多说了,它不但被开发人员经常运用,而且黑客们也常常使用它,总之用过的人知道它的强大之处,但是Iframe有个致命的"BUG"就是iframe的高度无法自 ...
- fir.im 持续集成技术实践
互联网时代,人人都在追求产品的快速响应.快速迭代和快速验证.不论是创业团队还是大中型企业,都在探索属于自己的敏捷开发.持续交付之道.fir.im 团队也在全面实施敏捷,并推出新持续集成服务 - flo ...
- TreeSet源码分析
第1部分 TreeSet介绍 TreeSet 是一个有序的集合,它的作用是提供有序的Set集合.它继承于AbstractSet抽象类,实现了NavigableSet<E>, Cloneab ...
- 在Adapter中如何关闭当前Activity
很多时候我们需要在点击adapter条目的时候关闭当前界面,把所点击条目的信息带到前一个界面,同时关闭当前界面. 这个 时候就需要在adapter对某一个点击事件做处理. 代码如下: holder.l ...
- android调用系统相机
Intent intent = new Intent(); intent.setPackage("com.android.camera"); intent.setAction(Me ...
- convertView的疑问(软件管理器)
package com.hixin.appexplorer; import java.util.List; import android.app.Activity; import android.co ...