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通信的更多相关文章

  1. php简单实现socket通信

    socket通信的原理在这里就不说了,它的用途还是比较广泛的,我们可以使用socket来做一个API接口出来,也可以使用socket来实现两个程序之间的通信,我们来研究一下在php里面如何实现sock ...

  2. Linux下简单的socket通信实例

    Linux下简单的socket通信实例 If you spend too much time thinking about a thing, you’ll never get it done. —Br ...

  3. Android简单实现Socket通信,client连接server后,server向client发送文字数据

    案例实现的是简单的Socket通信,当client(Androidclient)连接到指定server以后,server向client发送一句话文字信息(你能够拓展其他的了) 先看一下服务端程序的实现 ...

  4. 简单的Socket通信

    Socket简介 Socket又称"套接字",应用程序通常通过"套接字"向网络发出请求或者应答网络请求. 服务端步骤: • socket:创建服务器socket ...

  5. Day 6-2简单的socket通信

    什么是socket? Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口.在设计模式中,Socket其实就是一个门面模式,它把复杂的TCP/IP协议族隐藏在Socket接口后面 ...

  6. Java实现简单的socket通信

    今天学习了一下java如何实现socket通信,感觉难点反而是在io上,因为java对socket封装已经很完善了. 今天代码花了整个晚上调试,主要原因是io的flush问题和命令行下如何运行具有pa ...

  7. C#版 Socket编程(最简单的Socket通信功能)

    示例程序是同步套接字程序,功能很简单,只是客户端发给服务器一条信息,服务器向客户端返回一条信息:这里只是一个简单的示例,是一个最基本的socket编程流程,在接下来的文章中,会依次记录套接字的同步和异 ...

  8. Java 实现简单的 Socket 通信

    Java socket 封装了传输层的实现细节,开发人员可以基于 socket 实现应用层.本文介绍了 Java socket 简单用法. 1. 传输层协议 传输层包含了两种协议,分别是 TCP (T ...

  9. 简单的Socket通信(简单的在线聊天)---winform

    注:本博客适合刚开始学习winform程序的初学者,大牛请绕道(跪求大牛指导文中不足) .....10w字废话自动省略,直接开始正题. 首先从最基本的建立winform开始(本项目用的Vs2017) ...

随机推荐

  1. Web层框架对网站中所有异常的统一解决

    一个网站的异常信息作为专业的人士,是不会轻易暴露给用户的,因为那样狠不安全,显得你漏是一回事,只要还是考虑到网站的数据安全问题,下面给大家分享一下一些常见的web层框架是如何处理统一的异常. 之前都是 ...

  2. 阿里云centos 安装和配置 DokuWiki

    安装 1) 添加虚拟主机:由于我的 阿里云CentOs服务器 安装了oneinstack的一键部署PHP.JAVA.Nginx等环境,所以域名配置很方便,照着文档一步一步做就可以了 cd /root/ ...

  3. ASP.NET Cookie和Session

    Cookie和Session C#在服务器,JS在客户端 客户端验证不能代替服务端验证 Http HTTP属于应用层,HTTP 协议一共有五大特点:1.支持客户/服务器模式;2.简单快速;3.灵活;4 ...

  4. J2EE struts2MVC应用在线书签1

    序:之前花了一天研究了一下filter,虽然是实现了MVC模式开发了 WebBookmark,但是代码过于冗长,集中在filter中使用if语句不易阅读,为了体现两份作业的不同点,我决定学习 Java ...

  5. poj3160强连通分量加dfs

    After retirement as contestant from WHU ACM Team, flymouse volunteered to do the odds and ends such ...

  6. myeclipse/eclipse 配置SSM框架错误之一解决方法

    报错如下: 1. [org.springframework.web.context.ContextLoader] - Root WebApplicationContext: initializatio ...

  7. 九思,OA协同九大设计要点

    伴随着产品线的丰富和客户数量的增加,我们发现烂尾项目也与日俱增,客户和OA公司之间的矛盾日益尖锐,一套好OA系统远非增加几个特色功能这么简单,套用孔子"君子有九思"的话,好的OA系 ...

  8. Python学习之路-Day1-Python基础

    学习python的过程: 在茫茫的编程语言中我选择了python,因为感觉python很强大,能用到很多领域.我自己也学过一些编程语言,比如:C,java,php,html,css等.但是我感觉自己都 ...

  9. Python实现RNN

    一般的前馈神经网络中, 输出的结果只与当前输入有关与历史状态无关, 而递归神经网络(Recurrent Neural Network, RNN)神经元的历史输出参与下一次预测. 本文中我们将尝试使用R ...

  10. sql查询优化整理

    1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引. 2.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索 ...