- # Include <iostream>
- # Include <Winsock. h>
- # Pragma comment (Lib, "wsock32.lib ")
- Using namespace STD;
- Int main ()
- {
- Wsadata data;
- // Load the class library
- Wsastartup (makeword (1, 1), & data );
- // Initialize the socket
- Socket serversocket = socket (af_inet, sock_stream, 0 );
- // Set the bound information to bind this socket
- Sockaddr_in serveraddress;
- Serveraddress. sin_family = af_inet;
- Serveraddress. sin_port = htons (9999 );
- Serveraddress. sin_addr.s_un.s_addr = htonl (inaddr_any );
- // Bind this socket
- BIND (serversocket, (sockaddr *) & serveraddress, sizeof (serveraddress ));
- // Start listening
- Listen (serversocket, 5 );
- Sockaddr_in clientaddress;
- Int Len = sizeof (clientaddress );
- While (1)
- {
- Cout <"Wait..." <Endl;
- Socket clientsocket = accept (serversocket, (sockaddr *) & clientaddress, & Len );
- Char sendbuffer [20];
- Strcpy (sendbuffer, "Hi, client I'm server, welcome you! ");
- Send (clientsocket, sendbuffer, strlen (sendbuffer), 0 );
- Char recvbuffer [20];
- Recv (clientsocket, recvbuffer, strlen (recvbuffer), 0 );
- Cout <recvbuffer <Endl;
- Cout <"bye" <Endl;
- Closesocket (clientsocket );
- }
- Return 0;
- }
This is a simple server code. In VC ++ 6.0, you only need to copy the code to run it completely.
The first time I saw this writing, I always felt incredible and too troublesome. After reading the instructions last night, the basic idea is clear and you can write the code yourself. C ++ is still a little difficult to get started.
I don't know why the socket in it is like this.
1: First load the class library
2: Initialize socket
3: bind the port and IP address (to form a class related to the port and IP address, and then set the attribute)
4: Start listening ......
In Java, you only need to set the IP address and port through the class constructor, and then call accept to enter the listening mode.
But fortunately, the idea is the same, but the rest of Java helps you. The following figure shows the effect of using telnet after the server runs.
I don't know why so many hot buzzwords come out. I know it's probably a char [] problem.