Test.cs Script
--------------------------------------------------------------------------------------------------------------- ------------------------------------
Using System.Collections;
Using System.Collections.Generic;
Using Unityengine;
Using Assemblycsharp;
Using System.Text;
Using System;
Using System.Threading;
public class Test:monobehaviour {
Private Jfsocket Mjfsocket;
Use this for initialization
void Start () {
Mjfsocket = Jfsocket.getinstance ();
}
Update is called once per frame
void Update () {
if (mjfsocket!=null) {
Debug.Log (MJFSOCKET.RECEIVE_MSG);
}
}
}
--------------------------------------------------------------------------------------------------------------- ------------------------------------
SocketClientTest.cs
--------------------------------------------------------------------------------------------------------------- ------------------------------------
Using Unityengine;
Using System.Collections;
Using System;
Using System.Threading;
Using System.Text;
Using System.Net;
Using System.Net.Sockets;
Using System.Collections.Generic;
Using System.IO;
Using System.Runtime.InteropServices;
Using System.Runtime.Serialization;
Using System.Runtime.Serialization.Formatters.Binary;
Namespace Assemblycsharp
{
public class Socketclienttest
{
Socket Client Object
Private Socket Clientsocket;
Single-Case mode
private static Socketclienttest instance;
public string receive_msg = "";
public static Socketclienttest getinstance ()
{
if (instance = = null)
{
Instance = new Socketclienttest ();
}
return instance;
}
Single-instance constructors
Socketclienttest ()
{
Create a socket object, where my connection type is TCP
Clientsocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);
Server IP Address
IPAddress IPAddress = Ipaddress.parse ("127.0.0.1");
Server port
IPEndPoint IPEndPoint = new IPEndPoint (ipAddress, 5209);
This is an asynchronous build connection that calls the Connectcallback method when the connection is established successfully
IAsyncResult result = Clientsocket.beginconnect (IPEndPoint, New AsyncCallback (Connectcallback), clientsocket);
Here is a time-out monitoring, when the connection is more than 5 seconds has not successfully indicated the timeout
BOOL Success = result. Asyncwaithandle.waitone (n, True);
if (!success)
{
Timeout
Closed ();
Debug.Log ("Connect Time Out");
}
Else
{
Debug.Log ("Successful connection with socket, open thread accepts server data");
The connection to the socket was successful, and the thread was opened to accept server data.
Thread thread = new Thread (new ThreadStart (receivesorketmsg));
Thread. IsBackground = true;
Thread. Start ();
}
}
private void Connectcallback (IAsyncResult asyncconnect)
{
Debug.Log ("connectsuccess");
}
private void Receivesorketmsg ()
{
Console.WriteLine ("Wait---");
Accept the data returned by the server in this thread
while (true)
{
if (!clientsocket.connected)
{
Disconnect from server jump out of loop
Debug.Log ("Failed to Clientsocket server.");
Clientsocket.close ();
Break
}
Try
{
Acceptance data saved to bytes
byte[] bytes = new byte[4096];
The Receive method waits until the server sends back a message
If there is no postback will always be here waiting.
int i = clientsocket.receive (bytes);
if (i <= 0)
{
Clientsocket.close ();
Break
}
Debug.Log (Encoding.ASCII.GetString (bytes, 0, i));
if (bytes. Length > 8)
{
Console.WriteLine ("Receive Server message: {0}", Encoding.ASCII.GetString (bytes, 0, i));
receive_msg = Encoding.ASCII.GetString (bytes, 0, i);
}
Else
{
Debug.Log ("Length is not > 8");
}
}
catch (Exception e)
{
Debug.Log ("Failed to Clientsocket error." + e);
Clientsocket.close ();
Break
}
}
}
Close socket
public void Closed ()
{
if (clientsocket! = null && clientsocket.connected)
{
Clientsocket.shutdown (Socketshutdown.both);
Clientsocket.close ();
}
Clientsocket = null;
}
}
}
--------------------------------------------------------------------------------------------------------------- ------------------------------------
Socket service-side code:
Using System;
Using System.Text;
Using System.Net.Sockets;
Using System.Net;
Using System.Threading;
Namespace SocketServerTest01
{
Class Program
{
private static byte[] result = new byte[1024];
private static int myprot = 5209; Port
Static Socket ServerSocket;
static void Main (string[] args)
{
Server IP Address
IPAddress IP = ipaddress.parse ("127.0.0.1");
ServerSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);
Serversocket.bind (New IPEndPoint (IP, Myprot)); Bind IP Address: port
Serversocket.listen (10); Set a maximum of 10 queued connection requests
Console.WriteLine ("Boot listener {0} succeeded", ServerSocket.LocalEndPoint.ToString ());
Sending data via Clientsoket
Socket clientsocket = serversocket.accept ();
while (true) {
Thread.Sleep (1000);
Sendmsg (Clientsocket);
}
}
<summary>
Send data to the client at the frequency of every second
</summary>
<param name= "Clientsocket" ></param>
public static void Sendmsg (Socket clientsocket)
{
Try
{
Clientsocket.send (Encoding.ASCII.GetBytes (Getrandomdata ()));
}
catch {
Console.WriteLine ("Server Exception");
Return
}
}
<summary>
Generate Random string
</summary>
<returns></returns>
private static string Getrandomdata ()
{
Random ran = new random ();
int x = ran. Next (50,200);
int y = ran. Next (20,100);
int z = 1000;
int ID = ran. Next (1,30);
String str = "ID:" +id+ "-x:" +x+ "-y:" +y+ "-Z:" +Z;
return str;
}
}
}
Unity3d script and C#socket server transfer data