Unity 实现简单socket通信收发消息

Unity中进行网络通信:三:unity客户端和Unity服务端互相发消息 一.目的 1.想知道:Unity中进行网络通信:unity客户端和Unity服务端互相发消息 二.参考 1.unity3D中使用Socket进行数据通信(三) https://blog.csdn.net/qq_38112703/article/details/82624502 三.操作:一:完成:在同一个Unity的同一个物体上面添加 服务端、客户端代码 1.版本 unity2018.4.0f1 vs2017 windows10 64位 1.运行结果... 阅读详情

服务端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;

namespace NetworkServer
{
    class Program
    {
        static void Main(string[] args)
        {
            /*创建一个socket对象*/
            //寻址方式 套接字类型 协议方式
            Socket tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            /*绑定监听消息IP和端口号*/
            IPAddress ip = IPAddress.Parse("192.168.1.101");
            EndPoint endPoint = new IPEndPoint(ip, 10001);
            tcpSocket.Bind(endPoint);//向操作系统申请一个ip和端口号
            Console.WriteLine("服务器端启动完成");


            /*开始监听客户端的连接请求*/
            tcpSocket.Listen(100);//最多可以接收100个客户端请求
            Socket socket = tcpSocket.Accept();//暂停当前线程,直到接收到客户端发来的连接请求;当接收到客户端的连接请求后,在本地服务器创建一个socket与客户端连接,并返回出来
            Console.WriteLine("有个客户端连接进来");

            /*向客户端发送消息*/
            string messge;
            messge = "你好,我有什么可以帮助到你吗";
            var date = ASCIIEncoding.UTF8.GetBytes(messge);
            socket.Send(date);


            /*从客户端接收消息*/
            byte[] bt = new byte[1024];//设置一个消息接收缓冲区
            int message = socket.Receive(bt);//该状态处于一个暂停状态,知道接收到消息,并返回字节数
            Console.WriteLine("接收到从客户端发来的消息:" + ASCIIEncoding.UTF8.GetString(bt));
            Console.ReadLine();
        }
    }
}

 

 

 

客户端 :

using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.Text;

public class Client : MonoBehaviour
{
    private Socket tcpSocket;

    private void Start()
    {
        //创建socket
        tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //连接服务器
        tcpSocket.Connect(IPAddress.Parse("192.168.1.101"), 10001);
        Debug.Log("连接服务器");
        //接收消息
        byte[] bt = new byte[1024];
        int messgeLength = tcpSocket.Receive(bt);
        Debug.Log(ASCIIEncoding.UTF8.GetString(bt));
        //发送消息
        tcpSocket.Send(ASCIIEncoding.UTF8.GetBytes("我有个问题"));
    }
}

 

先启动服务端

启动客户端

Unity学习之Socket通信 简单的socket通信学习笔记 阅读详情

相关推荐

【Unity】Socket网络通信(TCP) - 最基础的客户端通信流程

最基础的Unity客户端与服务端通讯流程代码,最简单的收发消息!

weixin_43453797的博客 6592

Unity【Multiplayer 多人在线】- Socket 通用客户端网络模块(二)、Receive 接收并处理数据

介绍 在阅读了罗培羽著作的Unity3D网络游戏实战一书后,博主综合自己的开发经验与考虑进行部分修改和调整,将通用的客户端网络模块和通用的服务端框架进行提取,形成专栏,介绍Socket网络编程,希望对其他人有所帮助。目录如下: 一、通用服务端框架 (一)、定义套接字和多路复用​​​​​​ (二)、客户端信息类和通用缓冲区结构 (三)、Protobuf 通信协议 (四)、数据处理和关闭连接 (五)、M...

当代野生程序猿 2531

unity使用Tcp/UDP协议网络通信实现(Socket简单应用)

服务器端: 1.打开vs,创建一个c#的控制台应用程序 代码如下 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.Net; namespace Socket服务器端 { class Program { static

梦想是世界和平 5024

Unity3D 网络游戏框架(二、同步Socket)

0基础Unity网络编程

qq_39596597的博客 1780

Unity 与C#服务器 Socket的UDP通信

前言这几天简单的研究了下Unity和服务器有关Socket的UDP通信,因为帧同步当中,UDP相比TCP是更适合的那种,因为UDP在网络环境较差时,波动更小,实时性也更高,可以更好的解决卡顿的问题(具体的小伙伴们可自行查阅资料)。当然使用UDP造成的开发量与开发难度会更大。在这里,我就先记录下自己这几天实现的udp简单的客户端与服务器的发送与接收功能的demo代码。注意1.本文是接着之前Socke...

王王王渣渣的博客 7177

【网络编程知识】使用Socket通信,做一个简单的多人聊天室

Socket 作为网络编程超级重要的一个知识点,对于程序员自然是一个必备的东西。 正好最近在看一些Socket套接字的内容,就想着能不能使用Socket做一个简单的通信功能,来加深对Socket的认知。 所以这篇文章就来使用Socket来简单制作一个多人聊天室,看看Socket到底怎样进行使用。

努力前行,总会成为自己心中的那道光 1万+

Unity Socket不断接受和发送消息

【代码】Unity Socket不断接受和发送消息。

weixin_43780907的博客 482

华东师范大学2020机试题解

1.统计卡牌的值 #include<iostream> #include<string> #include<vector> //#include<algorithm> using namespace std; int main() { int n; cin>>n; int answer=0; for(int i=0;i<n;++i) { string str; ci

qq_42254342的博客 1897

Unity3d C# Socket异步发送与接收数据

在网络游戏开发中,一些游戏需要使用长连接的方式进行网络通信,即使用Socket建立长连接。那么在Unity3d中,如何使用C#与服务端建立长连接呢?为什么 要说使用异步呢?我们知道,在Unity3d中,每个游戏画面的播放都是以帖的概念循环播放的。而且只能在UI线程中播放,在其它线程不可以操作UI有关的东西,这都是网络通信需要解决的问题。 使用Socket创建连接 众所周知,在游戏客户端启动之后,一......

王广帅--游戏开发-服务器开发 4370

新手必看:TwinCAT死活扫不到倍福CX5020?别慌,先检查这3个地方(附静态IP配置)

本文详细介绍了TwinCAT软件无法扫描到倍福CX5020控制器的常见问题及解决方案。从网络连通性检查、系统环境配置到静态IP设置,提供了一套完整的排查流程和优化建议,帮助新手快速解决通信问题,确保设备稳定运行。

weixin_27219587的博客 359

武汉理工大学数据结构综合实验——连连看游戏综合实践

文章目录实验目的主要仪器设备及耗材一、实验要求二、分析与设计(非线性结构)1.数据结构的设计2.核心算法设计一条直线消子两条直线消子三条直线消子初始化游戏地图搜寻路径提示和重排3.测试用例设计4.测试效果总结 实验目的 (1)线性结构实验目的 调研连连看游戏,了解连连看游戏的功能和规则等 掌握集成开发工具VS2019的使用和C++的基础编程 了解MFC框架 了解线性结构,掌握数组的遍历、消子和胜负判断等算法 了解企业软件开发过程,应用迭代开发思路进行项目开发,养成良好的编程习惯和培养软件工程化思维 .

mo_zhe的博客 7605

unity简单本地服务器的创建

using System.Collections;using System.Collections.Generic;using UnityEngine;using System.Net.Sockets;using System.Net;using System;using System.Text;//工具类public class NetworkManager {    #region  单例 ...

wu392179786的博客 4382

Profinet从站开发初体验:用p-net开源库和树莓派快速搭建一个IO设备模拟器

本文详细介绍了如何使用p-net开源库和树莓派快速搭建Profinet从站IO设备模拟器。从开发环境准备、p-net源码编译到设备模拟器功能实现,提供了全流程实战指南,帮助开发者快速掌握工业通信协议开发技巧,适用于工业自动化领域的设备互联测试与验证。

weixin_30384217的博客 380

tcp unity 图片_Unity 简易聊天室(基于TCP)(2)

客户端用Unity开发,主要就是搭建一下聊天室的UI界面:输入框,聊天内容显示框,发送按钮灰色背景的就是Message,也就是聊天内容的显示框,是一个Text类型,这里创建UI方面就不多讲了在Canvas下挂一个ChatManager脚本using System;using UnityEngine;using System.Net.Sockets;using System.Net;using Un...

weixin_39623273的博客 174

Ubuntu20.04安装Eigen3.3.7、模板类Sophus和Ceres

Sophus的使用必须依赖3.3以上的Eigen版本。如果版本太低,Sophus库将无法安装使用。

qq_62964142的博客 3419

Open3D 计算点云的倒角距离(Chamfer Distance)【2025最新版】

;Chamfer Distance距离可以计算生成点云数据与标签点云数据之间的平均最短点距离。Open3D可以直接用来计算点云的Chamfer Distance距离。博客长期更新,本文最近一次更新时间为:2025年2月18日。

点云侠的博客 3245

unity客户端框架 网络框架

...

qq_36559726的博客 1335

OpenClaw实战四|内容创作全流程AI助理:自动撰稿+智能剪辑+多平台发布,一人顶一个内容团队

AI替代的是「写稿、剪辑、发布」这种流水线工作,真正让你解放出来,去做选题、创意、人设、变现这些高价值的事。OpenClaw这套内容创作全流程AI助理,最大的价值不是「帮你发内容」,而是让一个人,拥有一个内容团队的产能。不管是个人博主、小团队,还是企业新媒体,都能用零代码的方式,快速搭建属于自己的自动化内容矩阵。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 585

Unity网络基础客户端代码

【代码】Unity网络基础客户端代码。

2302_80274807的博客 119

基于CST的PCB通孔三维建模实例

本文简明扼要地描述了如何利用CST的参数化脚本快速生成PCB的通孔三维模型,非常适合于进行快速精准的PCB参数分析。

一只豌豆象的博客 1820

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

Unity网络基础服务端代码(基础)

【代码】Unity网络基础服务端代码(基础)

2302_80274807的博客 115

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

在Unity中实现TCP通信(附完整工程)

本篇博客讲述了如何在unity中实现简单的TCP通信功能,包含服务器端与客户端,并配有简易的交互界面,用来显示一些状态信息以及接收和发送的数据。

qq_39748832的博客 2万+

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【Unity】Socket网络通信(TCP) - 实现简单的多人聊天功能

unity实现非常简单的多人聊天功能,内含工程文件下载地址,免积分下载!

weixin_43453797的博客 9148

【游戏开发实战】Unity使用Socket通信实现简单的多人聊天室(万字详解 | 网络 | TCP | 通信 | Mirror | Networking)

教你Unity使用Socket通信实现简单的多人聊天室(网络 | TCP | 通信 | Mirror | Networking)

linxinfa的专栏 1万+

【游戏开发实战】用Go语言写一个服务器,实现与Unity客户端通信(Golang | Unity | Socket | 通信 | 教程 | 附工程源码)

【游戏开发实战】用Go语言写一个服务器,实现与Unity客户端通信(Golang | Unity | Socket | 通信 | 教程 | 附工程源码)

linxinfa的专栏 1万+

unity游戏开发-socket网络通信

本篇主要是分享基于unity的客户端socket网络通信方案。关于服务器的c#-socekt搭建放在了这里《基于C#的Tcp服务端通信》。其中关于socekt粘包断包的处理放在这里分享了《C# socket粘包断包处理》。 整体设计 如图所示,一共采用了两层封装来处理整个客户端的逻辑。 首先TcpClient脚本只处理最基础的连接建立,消息的发送和接收。 TcpClientMgr管理和穿件TcpClient。在利用好连接建立,消息收发的基础上再处理业务上的需求:心跳、消息等待、事件传递等。 T

FlyToCloud的博客 3827
上一篇: UGUI自动布局
下一篇: Unity C# 通过反射,通过类名、方法名调用方法
Young_Super
博客等级 码龄10年 26粉丝 62原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值