Unity uses C # for simple scoket connections and server-to-client communication

Source: Internet
Author: User
Tags getstream server port

Brief introduction:

Network programming is a very interesting thing, accidentally turned out a long time ago just began to look at the socket when writing an example, paste it out

A simple socket connection is implemented in unity, and a rich API is provided in C #, directly on the code.

Service-Side code:

[CSharp] View plain copy
Thread connectthread;//Current server listener sub-thread
public string address;//Current address
public int port;//current local port
TcpClient romoteclient;//Remote Client

Use this for initialization
void Start ()
{
Connectthread = new Thread (initserversocket);
Connectthread.start ();
}

<summary>
Instantiating a service-side socket
</summary>
public void Initserversocket ()
{
int buffersize = 8192;//buffer size
IPAddress IP = ipaddress.parse (address);
Create a new TCP connection and turn on listener threads
TcpListener TcpListener = new TcpListener (IP, port);
Tcplistener.start ();
Debug.Log ("Server-to-client completion, turn on TCP connection monitoring");
If you have a remote client connection, you get its object for communication at this time
Romoteclient = Tcplistener.accepttcpclient ();
Debug.Log ("Client connection starts local address port:" + romoteClient.Client.LocalEndPoint + "Remote Client address port:" + romoteClient.Client.RemoteEndPoint);
NetworkStream stream = Romoteclient.getstream ();
Do
{
Try
{
Get Connection data with Client
byte[] buffer = new Byte[buffersize];
int byteread = stream. Read (buffer, 0, buffersize);
if (Byteread = = 0)
{
Debug.Log ("Client disconnect");
Break
}
String msg = Encoding.UTF8.GetString (buffer, 0, byteread);
Debug.Log ("Data received from the client:" + msg + "Data length:" + byteread + "bytes");

}
catch (Exception ex)
{
Debug.Log ("Client exception:" + ex.) Message);
Shut down the thread to prevent overflow when the client has an exception or is disconnected
Tcplistener.stop ();
Break
}
} while (true);
}

<summary>
Server-side sends messages based on the current connection's remote client
</summary>
public void Sendmessagetoclient (www.yongshiyule178.com)
{
if (romoteclient! = null)
{
RomoteClient.Client.Send (Encoding.UTF8.GetBytes ("Hello Client, this is server!"));
}
}

<summary>
Turn off listener threads and connections when destroying
</summary>
void OnDestroy ()
{
if (romoteclient! = null)
Romoteclient.close ();
if (connectthread! = null)
Connectthread.abort ();
}
Client code:

[CSharp] View plain copy
public string serveraddress;//server address
public int port;//Server port
Private TcpClient localclient;//Current TCP Client
Private thread receivethread;//receive Server message thread
Private byte[] Resultbuffer = new byte[1024];//server returns stream bytes
private string resultstr;//Server return string

void Start ()
{
Connect to the service side
Initclientsocket ();
}

<summary>
Operations when destroying
</summary>
private void OnDestroy ()
{
if (localclient! = null)
Localclient.close ();
if (receivethread! = null)
Receivethread.abort ();
}

<summary>
Client instantiation of the socket connection
</summary>
private void Initclientsocket (www.thd1956.com/)
{
Localclient = new TcpClient (www.huayu521.com);
Try
{
The server address of the current client connection and the remote port
Localclient.connect (Ipaddress.parse (serveraddress), port);
Start receiving server message child threads
Receivethread = new Thread (socketreceiver);
Receivethread.start ();
Debug.Log ("Client-to-server completion, turn on Receive Message thread");
}
catch (Exception ex)
{
Debug.Log ("Client Connection Server Exception:" + ex.) Message);
}
Debug.Log ("Connect to server local address port:" + localClient.Client.LocalEndPoint + "remote server port:" + localClient.Client.RemoteEndPoint);
}

<summary>
Client sends a message to the server
</summary>
private void Sendmessagetoserver (www.huayyule.com)
{
Try
{
String clientstr = "Hello Server, this is client!";
Gets the current client's stream object and then converts the string to be sent to byte[] write send
NetworkStream stream = Localclient.getstream ();
byte[] buffer = Encoding.UTF8.GetBytes (CLIENTSTR);
Stream. Write (buffer, 0,www.dfgjpt.com buffer. Length);
}
catch (Exception ex)
{
Debug.Log ("The server generated an exception when sending a message:" + ex.) Message);
}
}

<summary>
Client detects receipt of server information sub-thread
</summary>
private void Socketreceiver ()
{
if (localclient! = null)
{
while (true)
{
if (localClient.Client.Connected = = False)
Break
In the Loop,
LocalClient.Client.Receive (Resultbuffer);
ResultStr = Encoding.UTF8.GetString (Resultbuffer);
Debug.Log ("Client Receives Server message:" + resultstr);
}
}
}
At this point, the panel fills in the address and port of the server, runs the service side, then runs the client, the client clicks to send the message, the servers receive the message, the client receives the message after the service sends the message. I am testing on two machines, debug as follows:

Service side:

Client:

Precautions:

1. Address of the server and client do not write wrong

2. Port on the server to ensure that it is not occupied

3. When communicating, keep the string encoding in a consistent format

4. Child thread life cycle, remember to destroy, in order to ensure that the main thread destroyed while destroying the child thread can use thread. IsBackground = True

Unity uses C # for simple scoket connections and server-to-client communication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.