Simple communication between a unity client and a C + + server _1

Source: Internet
Author: User
Tags htons

//Server# pragma onceusing namespacestd;# include<iostream># include<string># include<stdio.h># include<winsock2.h># pragma comment (lib, "Ws2_32.lib") # include "Tool.h"voidMain () {wsadata wsadata; SOCKET Listeningsocket; SOCKET newconnection;sockaddr_in serveraddr;sockaddr_in clientaddr;//Struct sockaddr_in//    {//Short sin_family; Sin_family: Represents the protocol family, generally af_inet. Represents the use of the TCP/IP protocol family//U_short Sin_port; Sin_port: Represents the port number 16 bits. Note the byte order//struct IN_ADDR sin_addr; SIN_ADDR: Represents a 32-bit IPV4 address. //Char sin_zero[8]; 0 additions to Sin_zero:8 bytes. //    }intClientaddrlen =sizeof(sockaddr_in);intPort =5150;intret;Chardatabuffer[1024x768];//int WSAStartup (WORD version, Lpwsadata lpwsadata);/*This function initializes the Windows Sockets DLL in the application, and the application can then call the API functions in the other Windows Sockets DLLs only after the function call succeeds. If 0 is returned successfully. Version represents the highest version of Winsock required by the program. Where the major version number is in low byte, the minor version number is in high byte. For example: Using version 1.2, the value of version 0x0201. You can also use Makeword (2, 2). WORD Makeword (BYTE blow,byte bhigh); Lpwsadata represents a pointer to Wsadata, which includes information about the native system.    It is the return value of struct Wsadata {WORD wversion;           The Representative recommends using the version number Word Whighversion; Represents the system's highest supported version number char Szdescription[wsadescription_len + 1];char Szsystemstatus[wsasysstatus_len + 1];unsigned Short imaxsockets;unsigned Short Imaxudpdg;char FAR * lpvendorinfo;};*/if(ret = WSAStartup (Makeword (2,2), &wsadata)! =0) {cout<< "Wsastart up isFailed with error\t "<< ret <<Endl;return;}/*socket Socket (int AF, int type, int protocol) AF: represents the protocol family, generally af_inet. Type: Represents a set of interface types, Sock_stream flow sockets, Sock_dgram datagram sockets flow on the socket data is borderless, reliable. Datagram sockets are bounded and unreliable (as opposed to flow sockets), the flow sockets are slow and the datagram is faster. The stream sockets are ordered, and the datagram sockets are unordered (the data that is sent later may be received first.) So the general TCP with the Liu socket, UDP with the datagram about the UDP protocol, the later chapter will give (well, may give, see if there is time) estimated that QQ message is UDP, specifically did not go to study--protocol: Specify the protocol used. such as: Ipproto_tcp, Pproto _UDP return value: Returns a new socket if no error occurred, otherwise returns Invalid_socket. *///Create a listening socket, the so-called monitoring, is to see if there is a client connection upif(Invalid_socket = = (Listeningsocket =sockets (Af_inet, Sock_stream, ipproto_tcp))) {cout<< "socket isFalied with error\t "<< wsagetlasterror () <<Endl; WSACleanup ();return;}//The byte sequence used by the native system is called: Native byte order//the byte sequence used by the network standard is called: Network byte order/*htons ()--native to Network (short) htonl ()--native to network (long) Ntohs ()--Network to native (short) Ntohl ()--Network to native (long)*/serveraddr.sin_family=Af_inet;serveraddr.sin_port=htons (port); ServerAddr.sin_addr.s_addr=htonl (inaddr_any);//Inaddr_any is the address specified as 0.0.0.0, which in fact represents an indeterminate address, or "all addresses", "arbitrary addresses". In general, each system is defined as a value of 0. //Binding Port//bind (SOCKET s, const struct SOCKADDR far *name, int namelen);//Next, for the server-side definition of this listener socket to specify a ground//Port so that the client knows which address to connect to//port, for which we want to call the bind () function, the function call returns 0 successfully, otherwise//back to Socket_errorif(Socket_error = = Bind (Listeningsocket, (sockaddr*) &serveraddr,sizeof(SERVERADDR))) {cout<< "bind isFalied with error\t "<< wsagetlasterror () <<Endl;closesocket (Listeningsocket); WSACleanup ();return;}//Monitor//int Listen (SOCKET s, int backlog);//after the server-side socket object is bound, the server side must establish a listening queue to receive the client's connection request. //The listen () function causes the server-side socket to enter the listening state and sets the maximum number of connections that can be established (the current maximum limit is 5 and the minimum value is 1). //The function call successfully returns 0, otherwise returns SOCKET_ERROR. if(Socket_error = = Listen (Listeningsocket,5) ) {cout<< "Listen isFalied with error\t "<< wsagetlasterror () <<Endl;closesocket (Listeningsocket); WSACleanup ();return;} cout<< "Now we is waiting a connection fromClient "<<Endl;cout<< "sizeofSockaddr_in:\t "<<sizeof(sockaddr_in) << "\tsizeof sockaddr\t" <<sizeof(SOCKADDR) <<Endl;//server-side accept connection requests from clients//SOCKET Accept (scoket s, struct sockaddr far *addr,int far *addrlen);//in order for the server side to accept client connection requests, use the Accept () function,//This function creates a new socket that is connected to the client socket, and the previously monitored socket continues to be in the listening state.//wait for someone else's connection request. The function call successfully returns a newly generated SOCKET object, otherwise returns Invalid_socket. if(Invalid_socket = = (Newconnection = Accept (Listeningsocket, (sockaddr*) &clientaddr, &Clientaddrlen)))  {cout<< "Accept isFalied with error\t "<< wsagetlasterror () <<Endl;closesocket (Listeningsocket); WSACleanup ();return;} cout<< "GetA Connect fromClient addr\t "<< Inet_ntoa (clientaddr.sin_addr) <<" \ T "<< Ntohs (Clientaddr.sin_port) <<Endl;//Reception of data//int recv (SOCKET s, char far *buf, int len, int flags);//Parameters://S is the ID of the socket//buf: Staging area to store received information//Length of Len:buf//Flags: The way this function is called//The return value is the length of the accepted string (in case there is no error)if(Socket_error = = (ret = recv (newconnection, DataBuffer,sizeof(DataBuffer),0)) {cout<< "recv isErrow with\t "<< wsagetlasterror () <<Endl;closesocket (newconnection); WSACleanup ();return;} Databuffer[ret]= ' \0';//wchar_t *temp = Tool::getsingleton ()->chartowchar (databuffer);//cout << "ret:\t" << ret << "\tdata\t" << temp << Endl;//temporarily do not know how to parse the Unity client sent over the Chinese,,, sad not, tried several methods, there is know can tell me undercout<< DataBuffer <<Endl;//End Socket Connection//It is easy to end the communication connection between the server and the client, which can be initiated by either end of the server or client .//just call Closesocket () and use this function to close the socket of the server-side listening state. //In addition, it should be called WSAStartup () when the program starts, and it needs to call WSACleanup () before it ends.//to notify the Winsock stack of the resources used to release the socket. Both of these functions are called successfully return 0, otherwise return socket_error. //int PASCAL far closesocket (SOCKET s);//parameter: s is the socket identification code;//int PASCAL far wsacleanup (void);closesocket (newconnection); WSACleanup ();}

Unity ClientusingUnityengine;usingSystem.Collections;usingSystem.Text;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.IO; Public classtestscoket:monobehaviour{voidStart () {conncetserver (); }    voidConncetserver () {IPAddress Ipadr= Ipaddress.parse ("10.0.0.22"); IPEndPoint ipEp=NewIPEndPoint (Ipadr,5150); Socket Clientscoket=Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);        Clientscoket.connect (IPEP); stringOutput = "Zhangsan";//Chinese temporarily do not know how to parse "Chinese"        byte[] Concent =Encoding.UTF8.GetBytes (output); //byte[] concent = Encoding.Unicode.GetBytes (output);        intCount =clientscoket.send (concent);        Debug.logerror (count); //byte[] response = new byte[1024]; //int bytesread = clientscoket.receive (response); //string input = Encoding.UTF8.GetString (response, 0, bytesread); //print ("Client Request:" + input);Clientscoket.shutdown (Socketshutdown.both);    Clientscoket.close (); }    Private voidconnectcallback (System.IAsyncResult ar) {debug.logerror ("Connection succeeded"); }}

Simple communication between a unity client and a C + + server _1

Related Article

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.