Photon Server engine (ii) Implementation of SOCKET/TCP/UDP Foundation and Unity chat Room

Source: Internet
Author: User

Photon Server engine (ii) Implementation of SOCKET/TCP/UDP Foundation and unity chat roomWhat do we usually say the most socket is, in fact, the socket is the TCP/IP protocol encapsulation, the socket itself is not a protocol, but a call interface (API).
With the socket, we can use the TCP/IP protocol. In fact, the socket is not necessarily associated with the TCP/IP protocol. The socket programming interface is designed to adapt to other network protocols as well. So, the advent of sockets just makes it easier for programmers to use the TCP/IP protocol stack, which is an abstraction of the TCP/IP protocol, thus forming some of the most basic function interfaces we know, such as Create, listen, connect, accept, send, Read and write, and so on.
The network has a section on the socket and TCP/IP protocol relationship is relatively easy to understand:

"TCP/IP is just a stack of protocols, just like operating systems, which must be implemented in a specific way, as well as providing an external interface for operations."
This is like the operating system will provide standard programming interfaces, such as the Win32 programming interface,
TCP/IP also provides the interface for programmers to do network development, which is the socket programming interface. ”

1. Principle of TCP protocol implementationTCP packets mainly include:
1. SYN packet: Request to establish a connected packet
2. ACK Packet: Response packet, indicating receipt of one of the other's packets
3. PSH Package: Normal data packet
4. Fin Package: Communication End Package
5. RST Package: RESET Connection
6. Urg Pack: Emergency hands

One complete TCP communication includes: Establish connection, data transfer, close connection
To establish a connection (three handshake):
1. The client establishes an active open by sending a SYN to the server, as part of the three-way handshake.
2, the server side should be a legitimate SYN loopback a syn/ack.
3. Finally, the client sends an ACK again. This completes the three-way handshake and enters the connection establishment state.
Data transmission:
1. Transmitting PSH packets to the data terminal
2. Receive data-side reply ACK Packets
Close connection (four breakup):
1. Actively close the connection at one end. Send fin packets to the other end.
2. The other end of the fin packet is received to respond to an ACK packet.
3. Send a fin package at the other end.
4. The original sender receiving the Fin packet sends an ACK to confirm it.

The following is a simple server-side implementation using the TCP protocol:
Using system;using system.collections.generic;using system.linq;using system.net;using System.Net.Sockets;using    System.text;using System.Threading.Tasks; Class Program {static void Main (string[] args) {//1, creating socket socket TCPServer = new socket            (ADDRESSFAMILY.INTERNETWORK,SOCKETTYPE.STREAM,PROTOCOLTYPE.TCP);            2, bind IP with port number 222.20.30.68 IPAddress IPAddress = new IPAddress (new byte[]{222,20,30,68}); EndPoint point = new IPEndPoint (ipaddress,7788),//ipendpoint is a class ip+ (point) that has been encapsulated on the Tcpserver.bind port, or a request to the operating system for a usable IP and port number used to do communication//3, start listening (waiting for client connection) Tcpserver.listen (100);//parameter is the maximum number of connections Console.WriteLine ("Start listening           ");            Socket clientsocket = tcpserver.accept ();//pauses the current thread until a client connects to it, and then the following code Console.WriteLine ("A client is connected");            Use the returned socket to communicate with the client string message = "Hello welcomes You";       byte[] data = Encoding.UTF8.GetBytes (message);//Encode a string to get a byte array of a string     Clientsocket.send (data);            Console.WriteLine ("Sends a hop data to the client");            byte[] Data2 = new byte[1024];//creates a byte array to be used as a container to take the data sent over by the client int length = clientsocket.receive (DATA2); String message2 = Encoding.UTF8.GetString (data2, 0, length);//convert byte data to a string Console.WriteLine ("A client has received a            Sent over the message: "+message2);        Console.readkey (); }    }

use of TcpListener:
Using system;using system.collections.generic;using system.linq;using system.net;using System.Net.Sockets;using    System.runtime.interopservices;using system.text;using System.Threading.Tasks;            Class Program {static void Main (string[] args) {//1,tcplistener has a layer of encapsulation on the socket, which itself creates a socket object            TcpListener listener = new TcpListener (Ipaddress.parse ("222.20.30.68"), 7788); 2, start the monitoring listener.            Start (); 3, wait for the client to connect over TcpClient client = listener.            AcceptTcpClient (); 4, get the data sent by the client NetworkStream stream = clients. GetStream ();//Get a network stream from this network stream can get the data sent by the client byte[] "data = new byte[1024];//a container to create a database to undertake data while ( true) {///0 indicates which index of the array begins to hold the data//1024 represents the maximum number of bytes read int length = stream.                Read (data, 0, 1024);//reads a string message = Encoding.UTF8.GetString (data, 0, length); Console.WriteLine ("Message Received:" + MESSAGe); } stream.            Close (); Client.            Close (); Listener.        Stop ();//Stops monitoring Console.readkey (); }    }

2. The principle of UDP protocol implementationThe UDP protocol adds multiplexing, separation and error detection functions to IP protocols. Features of UDP:
1, is no connection. Compared to the TCP protocol, the UDP protocol does not need to establish a connection before transmitting the data, and of course it does not release the connection.
2, is to do their best to deliver. This means that the UDP protocol cannot guarantee that the data can be delivered to the destination host accurately. There is no need to verify the UDP packets received.
3, is the message-oriented. That is, the UDP protocol encapsulates the data transmitted by the application layer in a UDP packet without splitting or merging. Therefore, the transport layer after receiving the other side of the UDP packet, will be removed after the header, the data intact to the application process.
4, no congestion control. Therefore, the transmission rate of the UDP protocol does not affect the congestion of the network.
5, UDP supports a pair of one or one-to-many, many-to-one and many-to-many interactive communication.
6, UDP head occupies a small, only 8 bytes.

The following is a simple server-side implementation using the UDP protocol:
Using system;using system.collections.generic;using system.linq;using system.net;using System.Net.Sockets;using         System.text;using system.threading;using system.threading.tasks;class Program {private static Socket udpserver; static void Main (string[] args) {//1, creating socket Udpserver = new Socket (Addressfamily.interne            TWORK,SOCKETTYPE.DGRAM,PROTOCOLTYPE.UDP);            2, bind IP with port number udpserver.bind (New IPEndPoint (Ipaddress.parse ("192.168.0.112"), 7788)); 3, receive data new Thread (ReceiveMessage) {IsBackground = true}.            Start ();            Udpserver.close ();        Console.readkey ();  } static void ReceiveMessage () {while (true) {EndPoint remoteendpoint                = new IPEndPoint (ipaddress.any, 0);                byte[] data = new byte[1024]; int length = Udpserver.receivefrom (data, ref remoteendpoint);//This method places the source of the data (Ip:port) on the second argument, string mEssage = Encoding.UTF8.GetString (data, 0, length); Console.WriteLine ("From IP:" + (Remoteendpoint as IPEndPoint). Address.tostring () + ":" + (Remoteendpoint as IPEndPoint).            Port + "received data:" + message); }        }    }

Use of UdpClient:
Using system;using system.collections.generic;using system.linq;using system.net;using System.Net.Sockets;using System.text;using System.Threading.Tasks;    Class Program {        static void Main (string[] args) {            //create UdpClient bound IP with port number            udpclient udpclient = new UdpClient ( New IPEndPoint (Ipaddress.parse ("192.168.0.112"), 7788));            while (true)            {                //Receive data                ipendpoint point = new IPEndPoint (ipaddress.any, 0);                byte[] data = udpclient.receive (ref point);//point to determine which IP the data is from which port number the return value is a byte array, which is our data                string message = Encoding.UTF8.GetString (data);                Console.WriteLine ("Message Received:" + message);            }            Udpclient.close ();            Console.readkey ();        }    }

3. Unity realizes chat room functionimplementation code for the client:
Using unityengine;using system.collections;using system.net;using system.net.sockets;using System.Text;using    System.threading;public class chatmanager:monobehaviour{public string ipaddress = "222.20.30.68";    public int port = 7788;    Public Uiinput TextInput;    Public UILabel Chatlabel;    Private Socket Clientsocket;    Private Thread t; Private byte[] data = new byte[1024];//container private string message = "";//message container//Use this for initializationvoid Start () {connecttoserver ();} Update is called once per framevoid Update () {if (message! = NULL && Message! = "") {Chatlabel.        text + = "\ n" + message; message = "";//Empty Message}} void Connecttoserver () {clientsocket = new Socket (addressfamily.internetwo        Rk,sockettype.stream, PROTOCOLTYPE.TCP);        Establish a connection with the server Clientsocket.connect (new IPEndPoint (Ipaddress.parse ("222.20.30.68"), 7788));        Create a new thread to receive the message T = new Thread (ReceiveMessage); T.start ();        }///<summary>///This thread method is used to loop receive messages///</summary> void ReceiveMessage () {while (true)            {if (clientsocket.connected = = false) break;            int length = clientsocket.receive (data);            Message = Encoding.UTF8.GetString (data, 0, length);        Chatlabel.text + = "\ n" + message;        }} void SendMessage (String message) {byte[] data = Encoding.UTF8.GetBytes (message);    Clientsocket.send (data);        } public void Onsendbuttonclick () {String value = Textinput.value;        SendMessage (value);    Textinput.value = "";                } void OnDestroy () {clientsocket.shutdown (Socketshutdown.both); Clientsocket.close ();//Close Connection}}

server-side implementation code:
Using system;using system.collections.generic;using system.linq;using system.net.sockets;using System.Text;using     system.threading;using system.threading.tasks;namespace _022_ Chat room _socket_tcp server Side {///<summary>///for communication with client        </summary> class Client {public string name=null;        Private Socket Clientsocket;        Private Thread t; Private byte[] data = new byte[1024];//This is a data container public Client (Socket s,string i) {Clientsocket            = S;            name = i;            Start a thread processing client's data receive T = new thread (ReceiveMessage);        T.start ();                private void ReceiveMessage () {//receives the client's data while (true) {                    Determine if the socket connection is disconnected before receiving the data (Clientsocket.poll (Selectmode.selectread)) {                    Clientsocket.close (); break;//jumping out of loop terminating thread execution} int LEngth = clientsocket.receive (data);                String message = Encoding.UTF8.GetString (data, 0, length);                When the data is received, the data is distributed to the client//Broadcast message program.broadcastmessage (MESSAGE,NAME);            Console.WriteLine ("Received" +name + "message:" + message); }} public void SendMessage (String message) {byte[] data = Encoding.UTF8.GetBytes (message            );        Clientsocket.send (data);        } public bool Connected {get {return clientsocket.connected;} }    }}

Using system;using system.collections.generic;using system.linq;using system.net;using System.Net.Sockets;using system.net.websockets;using system.text;using system.threading.tasks;namespace _022_ chat room _socket_tcp Server-side {class                program {static list<client> clientlist = new list<client> ();        <summary>//Radio messages///</summary>//<param name= "message" ></param> public static void Broadcastmessage (string message,string name) {var notconnectedlist = new list<            Client> (); foreach (var client in clientlist) {if (client. Connected) client.                SendMessage (name+ ":" +message);                else {notconnectedlist.add (client);            }} foreach (var temp in notconnectedlist) {clientlist.remove (temp); }} static void MaiN (string[] args) {int i = 0;            string name = NULL;            Socket tcpserver = new socket (addressfamily.internetwork,sockettype.stream, protocoltype.tcp);//create tcpServer Tcpserver.bind (New IPEndPoint (Ipaddress.parse ("222.20.30.68"), 7788),//set IP and Port tcpserver.listen (100);            Listen Port Console.WriteLine ("Server running ...");                while (true) {i = i + 1;                 if (i = = 1) {name = "Tom";}                else if (i = = 2) {name = "Alice";}                else {name = "other";}                Socket clientsocket = tcpserver.accept ();//accept client request Console.WriteLine ("User" +name+ "Connected!");                                Client client = new Client (clientsocket,name);//The logic that communicates with each client (send and receive messages) is placed inside the client class for processing            Clientlist.add (client); }                    }    }}

Open two clients. Remember to change the IP address in your code to the IP address of your PC. implementation results:




===================================================================================end. wish everyone a happy National day! next section get started with Photon server engine.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission, casually reproduced.

Photon Server engine (ii) Implementation of SOCKET/TCP/UDP Foundation and Unity chat Room

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.