Unity3d Online Game Socket communication

Source: Internet
Author: User
Tags server port

Online game is a person's interactive entertainment software application. Because it is interactive, of course, you need to understand each other's communications. This requires a communication socket: the protagonist we are going to implement today is the socket. The English literal of the socket is "hole" or "socket". As the English original intended. Like a multi-hole socket.

A computer machine is like a room full of sockets, each with a number, some with a 220 vac, and some with 110 volts of alternating current. Some offer cable TV programs. The customer software plugs into different numbered sockets and can get different services. Let's take a look at how player movement is communicated in the game:


Here is the Unity3d game communication socket implementation: BaseGameSocket.cs

@ Original: dongfu.luousing system;using system.collections.generic;using System.net.sockets;public abstract class  basegamesocket{//used to receive the service side sent over the buffer buff private byte[] _data_buffer; Buffer binary array from where to read private int _data_offset;//buffered binary array read how many bytes private int _data_size;//game ServerIP Address private String _    ip  private bool _is_read_head;//game server Port private int _port;//data command list to be sent to the server private list<packetout> _send_list =    New List<packetout> ();    Private Socket _sock;        Private Const int max_send_queue = 0x3e8;//empties the data, usually calling private void Clear () {this._ip = null when disconnecting the connection;        This._port = 0;        This._sock = null;        list<packetout> list = this._send_list; Lock (list) {this._send_list.        Clear ();        } This._is_read_head = false;        This._data_buffer = null;        This._data_offset = 0;    this._data_size = 0; }//closing the client's socket public void close () {try {socket socket = ThiS._sock; This.            Clear (); if (socket! = NULL) && socket. Connected) {socket.                Shutdown (Socketshutdown.both); Socket.            Close (); }} catch (Exception Exception) {uedebug.logerror ("Connect:" + Exception.            ToString ()); This.        Error (lang.getstring ("k3432")); }}//Connect game server public void Connect (string IP, int. port) {try {this}.            Close ();            THIS._IP = IP;            This._port = port;            This._sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); This._sock.            Nodelay = true; This._sock. BeginConnect (This._ip, This._port, new AsyncCallback (this.        OnConnect), This._sock); } catch (Exception Exception) {uedebug.logerror ("Connect:" + Exception.            ToString ()); This.        Error (lang.getstring ("k3432")); }}//assumes that the socket is not closed and continues to wait for server information, and the false information is started to read    private void Continueread () {try {if (this). isconnected) {This._sock. BeginReceive (This._data_buffer, This._data_offset, This._data_size-this._data_offset, Socketflags.none, new AsyncCallback (this.            OnRead), NULL); }} catch (Exception Exception) {uedebug.logerror (Exception.            ToString ()); This.        Error (lang.getstring ("k3432"));        }//sends the command from the send queue to the game server, private void Continuesend () {packetout state = null; list<packetout> list = this._send_list; Lock (list) {if (this._send_list.            Count = = 0) {return;            } state = this._send_list[0];            if (State.start) {return;        } State.start = true;        } Socket sock = State.sock; if (sock. Connected) {sock. BeginSend (state.buff, 0, State.buff.Length, Socketflags.none, new AsyncCallback (this.        OnSend), state); }}//sends a failure or error, the shut-down socket is usually a network-broken server that shuts down the protected void Error (String msg) {this.        Close (); This.    OnError (msg); }//programmers know that this is a destructor ~packedsocket () {this.    Close ();        } public int getsendqueuesize () {list<packetout> List = this._send_list; Lock (list) {return this._send_list.        Count;    }}//This function subclasses to process protected abstract void OnConnect ();//Assume first connection, parse message header private void OnConnect (IAsyncResult ret) {if (ret. AsyncState = = This._sock) {try {This._sock.                EndConnect (ret); This.                Readhead (); This.            OnConnect ();             } catch (Exception Exception) {Debug.log (Exception);    }}} protected abstract void OnError (string msg); protected abstract void Onpack (byte[] data),//have server information to start parsing, now parse the information header and then parse the message body private void OnreaD (IAsyncResult ar) {try {if (this). isconnected) {int num = This._sock.                EndReceive (AR);                This._data_offset + = num; if (num <= 0) {} else if (this._data_offset! = This._ Data_size) {this.                Continueread ();                    } else if (this._is_read_head) {int num2 = Bitconverter.toint32 (this._data_buffer, 0); This.                ReadData (NUM2); } else {this.                    Onpack (This._data_buffer); This.                Readhead ();       }}} catch (Exception Exception) {Debug.log (Exception); }//assumes that the command was sent successfully. Check to see if the Send queue has any commands that need to be sent.

Suppose there is a continuation of the Send private void OnSend (IAsyncResult ar) {packetout asyncstate = ar. AsyncState as Packetout; Socket sock = Asyncstate.sock; if (sock. Connected) {sock. EndSend (AR); list<packetout> list = this._send_list; Lock (list) {if (this._send_list. Contains (asyncstate)) {this._send_list. Remove (asyncstate); }} this. Continuesend (); }//Read message body private void readdata (int pack_len) {this._is_read_head = false; This._data_size = Pack_len; This._data_offset = 4; This._data_buffer = new Byte[this._data_size]; This. Continueread (); }//Read message header private void Readhead () {this._is_read_head = true; This._data_size = 4; This._data_offset = 0; This._data_buffer = new Byte[this._data_size]; This. Continueread (); }//detailed sending information, first send data to send queue publIC void Send (byte[] buff) {if (this. isconnected) {packetout item = new Packetout {start = false, Buff = Buff , sock = This._sock}; int count = 0; list<packetout> list = this._send_list; Lock (list) {this._send_list. ADD (item); Count = This._send_list. Count; } if (Count > 0x3e8) {} else {this. Continuesend (); }}} public bool IsClosed {get {return (This._sock = = null); }} public bool IsConnected {get {return (This._sock! = null) && THIS._SOCK.C onnected); }}private class Packetout {public byte[] buff; Public Socket sock; public bool start; }}



Unity3d Online Game Socket 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.