019-directly develop Online Game 2 using Socket/tcp

Source: Internet
Author: User

Today, we continue to learn about the network. Today, data transmission is divided into two parts, one is the beginning of MySQL. Not much nonsense.

We actually know that in Vs, there is a mechanism of sticking to the package and subcontracting for internal optimization. So how should we transfer and send data? We use bitconverter. the getbytes class converts all strings into four bytes. We create a class message on the tcp client and write down the following dynamic message:

Public class message {public static byte [] getbytes (string data) {// first, we get a byte array byte [] databytes = encoding. utf8.getbytes (data); // calculate the length of int datalength = data. length; // create a new array byte [] lengthbyte = bitconverter. getbytes (datalength); // get the byte array Length byte [] newbytes = lengthbyte. concat (databytes ). toarray (); Return newbytes ;}}

Then write in program

 for (int i = 0; i < 100; i++)            {                clientSocket.Send(Message.GetBytes(i.ToString()));            }

Then write the message on the TCP server, as shown below:

Private byte [] DATA = new byte [1024]; private int startindex = 0; // start indexing public byte [] data {get {return data ;}} public int startindex {get {return startindex ;}// what public int remainsize {get {return data is remaining. length-startindex ;}} public void addcount (INT count) {startindex + = count;} // read data public void readmessage () {While (true) {// if the data length is less than 4, if (startindex <= 4) return; // get the length of the transmitted data, because toint32 only parses the first four bytes at a time, in this way, we can see several pieces of data in the array: int COUNT = bitconverter. toint32 (data, 0); If (startindex-4)> = count) {// The index minus 4 is the actual data length, and the data string S = encoding is accepted. utf8.getstring (data, 4, count); console. writeline ("parsed data:" + S); // update the data array. copy (data, Count + 4, Data, 0, startindex-4-count); startindex-= (count + 4) ;}else {break ;}}}

Write in the TCP Program

  static Message msg = new Message();
Static void acceptcallback (iasyncresult AR) {socket serversocket = ar. asyncstate as socket; socket clientsocket = serversocket. endaccept (AR); string msgstr = "Hello client, hello... "; byte [] DATA = encoding. utf8.getbytes (msgstr); clientsocket. send (data); clientsocket. beginreceive (MSG. data, MSG. startindex, MSG. remainsize, socketflags. none, effececallback, clientsocket); serversocket. beginaccept (accept Callback, serversocket);} static void effececallback (iasyncresult AR) {socket clientsocket = NULL; try {clientsocket = ar. asyncstate as socket; int COUNT = clientsocket. endreceive (AR); If (COUNT = 0) {clientsocket. close (); return;} MSG. addcount (count); MSG. readmessage (); clientsocket. beginreceive (MSG. data, MSG. startindex, MSG. remainsize, socketflags. none, effececallback, clientsocket);} c Atch (exception e) {console. writeline (E); If (clientsocket! = NULL) {clientsocket. Close ();}}}

In this way, write.

Next we will not talk about the use of some Mysql Data,

// Create a connection string connstr = "database = text002; Data Source = localhost; Port = 3306; user id = root; Password = root ;"; mysqlconnection conn = new mysqlconnection (connstr); Conn. open (); # Region Query // mysqlcommand cmd = new mysqlcommand ("select * from user", Conn); // mysqldatareader reader = cmd. executereader (); // while (reader. read () // {// string username = reader. getstring ("username"); // string Password = reader. getstring ("password"); // console. writeline (username + ":" + password); //} // reader. close (); # endregion # Region insert // string username = "hello"; string Password = "world "; // mysqlcommand cmd = new mysqlcommand ("insert into user set [email protected], [email protected]", Conn); // cmd. parameters. addwithvalue ("UN", username); // cmd. parameters. addwithvalue ("PWD", password); // cmd. executenonquery (); # endregion Conn. close (); // disconnect the console. readkey ();

That's all.

019-directly develop Online Game 2 using Socket/tcp

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.