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. bzoj2884 albus就是要第一个出场

    Description 已知一个长度为n的正整数序列A(下标从1开始), 令 S = { x | 1 <= x <= n }, S 的幂集2^S定义为S 所有子集构成的集合.定义映射 f ...

  2. FrameBuffer系列 之 介绍

    1.     来由 FrameBuffer是出现在2.2.xx内核当中的一种驱动程序接口.Linux工作在保护模式下,所以用户态进程是无法象 DOS 那样使用显卡 BIOS里提供的中断调用来实现直接写 ...

  3. [瞎玩儿系列] 使用SQL实现Logistic回归

    本来想发在知乎专栏的,但是文章死活提交不了,我也是醉了,于是乎我就干脆提交到CNBLOGS了. 前言 前段时间我们介绍了Logistic的数学原理和C语言实现,而我呢?其实还是习惯使用Matlab进行 ...

  4. WPF 自定义ColorDialog DropDownCustomColorPicker

    今天分享一个 WPF 版的ColorDialog,该控件源自 这里,不过笔者已经该控件做了大量的修改工作,以适应自己的产品需求,闲话少说,先看看效果图: 1.DropDownCustomColorPi ...

  5. 创建并发布npm包

    1.npm官网创建npm账户 npm网站地址:https://www.npmjs.com/ npm网站注册地址:https://www.npmjs.com/signup 2.命令行工具登录npm np ...

  6. Java中的锁分类

    在读很多并发文章中,会提及各种各样锁如公平锁,乐观锁等等,这篇文章介绍各种锁的分类.介绍的内容如下: 公平锁/非公平锁 可重入锁 独享锁/共享锁 互斥锁/读写锁 乐观锁/悲观锁 分段锁 偏向锁/轻量级 ...

  7. Mqtt服务器搭建

    .bg { background: #99CC99 } Mqtt服务器搭建 测试环境:CentOS64位 1.安装基础软件 yum install gcc-c++ yum install cmake ...

  8. Power Pivot表属性无法切换回表预览模式的问题

    近期Office365用户升级后解决了在Power Pivot中输入中文的问题,但是同时也带来了一个新的问题就是表属性窗口默认为“查询编辑器”模式,且无法切换回“表预览”模式. 本文和您分享在这种情况 ...

  9. hdu1068 Girls and Boys 二分匹配

    题目链接: 二分匹配的应用 求最大独立集 最大独立集等于=顶点数-匹配数 本体中由于男孩和女孩的学号是不分开的,所以匹配数应是求得的匹配数/2 代码: #include<iostream> ...

  10. Java线程池总结

    前一篇文章Java中实现多线程关键词整理中介绍了Java中创建多线程的各种办法,里面提到了线程池,这里对Java中的线程池做一个总结. 1. 关于ThreadPoolExecutor 为了更好地控制多 ...