Network Socket Programming (2) --- Client

xiaoxiao2021-03-06  14

In fact, only a difference between the client and the server side

1) No binding port, IP, and protocol

2) No listening message

3) The client has an operation of the connection server side (Connect)

Do one thing before writing the client (of course you can not do),

That is to add several projects in a work space.

That is to add (Add Now Project) project in that Workspace.

The following is the specific code

#include #include

INT main () {// ------------------------------------------- ---- // Use WSAStartup to negotiate the protocol version number Word WVersionRequested; wsadata wsadata; int Err; WVersionRequested = MakeWord (1, 1); err = WSAStartup (WversionRequested, & Wsadata); if (Err! = 0) {Return 0 } If (Lobyte (Wsadata.WVersion)! = 1 || Hibyte (Wsadata.wversion)! = 1) {wsacleanup (); return 0;} Socket SocketClient; SocketClient = Socket (AF_INET, SOCK_STREAM, 0); // -------------------------------------------------- ------------- // Use connection to connect to the server // Connect to the server // to specify the server's address, port, and address family sockaddr_in clientservice; clientservice.sin_addr.s_un.s_addr = INET_ADDR ("127.0.0.1"); clientService.sin_Family = AF_INET; ClientService.sin_Port = HTONS (27015); // ----------------------- ------------------------------------------ // Connect the server IF with CONNECT ( Connect (socketclient, (socketdr *) & clientservice, sizeof (clientservice)) == Socket_ERROR) {Printf ("failed to connect./n"); wsacleanup (); return 0;} // -------- ------------------- -------------------------------------- // Solder connection successfully calls the RECV receiving message Char recvbuffer [50]; recv (socketClient, Recvbuffer, 50, 0); Printf ("% s", recvbuffer; // --------------------- ------------------------------------------ // Send a message to the server Send (SocketClient, "This Is Client Message", SIZEOF ("This Is Client Message" 1,0);

/ / -------------------------------------------------------------------------------------------- ---------------- // Do the final ending CLOSESOCKET (SOCKETCLIENT); wsacleanup (); return 0;}

This will communicate with the server.

Of course, when you write the client, you have to connect the WS2_32.lib file as the write server side, otherwise the compiler is not connected.

This is the simplest DOS-based communication software

Next, I will use multithreading to write a communication software based on Window graphics window.

转载请注明原文地址:https://www.9cbs.com/read-50087.html

New Post(0)