Skip to content
Snippets Groups Projects
Commit 9d0783ad authored by florian.hassler's avatar florian.hassler
Browse files

add tcp and udp test

parent 5bb0a8fa
No related branches found
No related tags found
No related merge requests found
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!78 &1
TagManager:
serializedVersion: 2
tags: []
layers:
- Default
- TransparentFX
- Ignore Raycast
-
- Water
- UI
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
m_SortingLayers:
- name: Default
uniqueID: 0
locked: 0
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!5 &1
TimeManager:
m_ObjectHideFlags: 0
Fixed Timestep: 0.02
Maximum Allowed Timestep: 0.33333334
m_TimeScale: 1
Maximum Particle Timestep: 0.03
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!310 &1
UnityConnectSettings:
m_ObjectHideFlags: 0
m_Enabled: 0
m_TestMode: 0
m_TestEventUrl:
m_TestConfigUrl:
m_TestInitMode: 0
CrashReportingSettings:
m_EventUrl: https://perf-events.cloud.unity3d.com/api/events/crashes
m_Enabled: 0
m_CaptureEditorExceptions: 1
UnityPurchasingSettings:
m_Enabled: 0
m_TestMode: 0
UnityAnalyticsSettings:
m_Enabled: 0
m_InitializeOnStartup: 1
m_TestMode: 0
m_TestEventUrl:
m_TestConfigUrl:
UnityAdsSettings:
m_Enabled: 0
m_InitializeOnStartup: 1
m_TestMode: 0
m_EnabledPlatforms: 4294967295
m_IosGameId:
m_AndroidGameId:
m_GameIds: {}
m_GameId:
PerformanceReportingSettings:
m_Enabled: 0
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!937362698 &1
VFXManager:
m_ObjectHideFlags: 0
m_IndirectShader: {fileID: 0}
m_CopyBufferShader: {fileID: 0}
m_SortShader: {fileID: 0}
m_RenderPipeSettingsPath:
m_FixedTimeStep: 0.016666668
m_MaxDeltaTime: 0.05
# SimpleUnityTCP 🖧
A simple **demo-project** to show how **TCP** communication works on **Unity** environment, builded with **C#** and using [System.Net.Sockets](https://docs.microsoft.com/es-es/dotnet/api/system.net.sockets?view=netframework-4.7.2).
The main porpouse of this repo is to show the TCP communication on runtime, but also to provide a pretty commented and clear code so everyone else that wants to implement that kind of communication will be able without wasting a lot of time.
## Video-Example 📲
<p>
<img src="example_app.gif" alt="example_app gif"/>
</p>
## How to Use 💻
If you only want to see the app working, just run the ``SimpleTCP.exe`` which is located on the ``build`` directory.
If you want to open the project, you will need to have **Unity** installed with the **version 2017 or higher**.
If you only want to scratch the code, either inside the unity project or simply dragging the **.cs** classes on your editor, you have to watch on to this classes, which are located on ``Assets``:
* ``Server.cs``
* ``Client.cs``
## More Explanations 📡
**Note:** Unity do not allow the *save-use* of **Multi-Threading**, so the application is using **Co-routines** instead.
The stablished communication and workflow stablished right now follows the next order:
* **Start the Server** and let him waiting for client connections.
* **Start the Client** and connect him to the server.
* **Server waits** for client messages...
* **Client send** the message *Close* to the server.
* **Server recives** that *Close* message.
* **Server send a response** to the client, sending the same message, *Close*.
* **Client recives** the message, **close the connection** with the server and shuts down.
* **Server close the connection** with the client.
* **Server shuts down**
\ No newline at end of file
SimpleUnityTCP/example_app.gif

198 KiB

%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: Player
m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0}
m_ShaderKeywords:
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 0, y: 0}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 0, y: 0}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _GlossMapScale: 1
- _Glossiness: 0.892
- _GlossyReflections: 1
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 0, b: 0, a: 1}
- _EmissionColor: {r: 0.16981131, g: 0.09371662, b: 0.09371662, a: 1}
...@@ -440,7 +440,7 @@ GameObject: ...@@ -440,7 +440,7 @@ GameObject:
m_Icon: {fileID: 0} m_Icon: {fileID: 0}
m_NavMeshLayer: 0 m_NavMeshLayer: 0
m_StaticEditorFlags: 0 m_StaticEditorFlags: 0
m_IsActive: 1 m_IsActive: 0
--- !u!81 &534669903 --- !u!81 &534669903
AudioListener: AudioListener:
m_ObjectHideFlags: 0 m_ObjectHideFlags: 0
...@@ -654,7 +654,7 @@ MeshRenderer: ...@@ -654,7 +654,7 @@ MeshRenderer:
m_RenderingLayerMask: 1 m_RenderingLayerMask: 1
m_RendererPriority: 0 m_RendererPriority: 0
m_Materials: m_Materials:
- {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} - {fileID: 2100000, guid: fbc99dbc501bd984aa53dd51057e0b31, type: 2}
m_StaticBatchInfo: m_StaticBatchInfo:
firstSubMesh: 0 firstSubMesh: 0
subMeshCount: 0 subMeshCount: 0
......
...@@ -5,16 +5,34 @@ using UnityEngine; ...@@ -5,16 +5,34 @@ using UnityEngine;
public class CameraController : MonoBehaviour public class CameraController : MonoBehaviour
{ {
public GameObject player; public GameObject player;
private UdpConnection connection;
private Vector3 offset; private Vector3 offset;
void Start() void Start()
{ {
offset = transform.position - player.transform.position; offset = transform.position - player.transform.position;
string sendIp = "127.0.0.1";
int sendPort = 8881;
int receivePort = 11000;
connection = new UdpConnection();
connection.StartConnection(sendIp, sendPort, receivePort);
}
private void Update()
{
foreach (var message in connection.getMessages()) Debug.Log(message);
connection.Send(Time.deltaTime.ToString());
} }
void LateUpdate() void LateUpdate()
{ {
transform.position = player.transform.position + offset; transform.position = player.transform.position + offset;
} }
void OnDestroy()
{
connection.Stop();
}
} }
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class UdpConnection
{
private UdpClient udpClient;
private readonly Queue<string> incomingQueue = new Queue<string>();
Thread receiveThread;
private bool threadRunning = false;
private string senderIp;
private int senderPort;
public void StartConnection(string sendIp, int sendPort, int receivePort)
{
try { udpClient = new UdpClient(receivePort); }
catch (Exception e)
{
Debug.Log("Failed to listen for UDP at port " + receivePort + ": " + e.Message);
return;
}
Debug.Log("Created receiving client at ip and port " + receivePort);
this.senderIp = sendIp;
this.senderPort = sendPort;
Debug.Log("Set sendee at ip " + sendIp + " and port " + sendPort);
StartReceiveThread();
}
private void StartReceiveThread()
{
receiveThread = new Thread(() => ListenForMessages(udpClient));
receiveThread.IsBackground = true;
threadRunning = true;
receiveThread.Start();
}
private void ListenForMessages(UdpClient client)
{
IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
while (threadRunning)
{
try
{
Byte[] receiveBytes = client.Receive(ref remoteIpEndPoint); // Blocks until a message returns on this socket from a remote host.
string returnData = Encoding.UTF8.GetString(receiveBytes);
lock (incomingQueue)
{
incomingQueue.Enqueue(returnData);
}
}
catch (SocketException e)
{
// 10004 thrown when socket is closed
if (e.ErrorCode != 10004) Debug.Log("Socket exception while receiving data from udp client: " + e.Message);
}
catch (Exception e)
{
Debug.Log("Error receiving data from udp client: " + e.Message);
}
Thread.Sleep(1);
}
}
public string[] getMessages()
{
string[] pendingMessages = new string[0];
lock (incomingQueue)
{
pendingMessages = new string[incomingQueue.Count];
int i = 0;
while (incomingQueue.Count != 0)
{
pendingMessages[i] = incomingQueue.Dequeue();
i++;
}
}
return pendingMessages;
}
public void Send(string message)
{
Debug.Log(String.Format("Send msg to ip:{0} port:{1} msg:{2}", senderIp, senderPort, message));
IPEndPoint serverEndpoint = new IPEndPoint(IPAddress.Parse(senderIp), senderPort);
Byte[] sendBytes = Encoding.UTF8.GetBytes(message);
udpClient.Send(sendBytes, sendBytes.Length, serverEndpoint);
}
public void Stop()
{
threadRunning = false;
receiveThread.Abort();
udpClient.Close();
}
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment