winsock教程- windows下的socket编程(c语言实现)
使用winsock进行socket 编程
这是一个学习windows下socket编程(c语言)的快速指南。这是因为一下代码片段只能运行在windows下。windows API中的socket编程部分叫做winsock。
你电脑上做出的任何网络通信背后基本上都有socket,它是一个网络的基本组成部分。举个例子说当你在浏览器键入www.google.com的时候,socket连接到google.com并且取回那个页面然后才能显示给你。任何聊天软件也是一样的比如skype gtalk
在你开始之前
这个教程假定你有基本的c编程能力,并且请下载Visuall c++ 2010 express
初始化winsock
首先需要这样初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
winsock函数包含在winsock2.H。你还需要link ws2_32.lib到你的程序以便使用这些函数。
WSAStartup函数用于启动或者初始化winsock库。它需要两个参数,第一个指定我们想要加载的版本,第二个是一个WSADATA结构体,它可以在winsock加载之后储存额外的数据。
如果有错误产生的话,WSAStartup会返回一个非零值。并且可以用WSAGetLastError 来获取更多信息。
好了,下一步就来创建一个socket。
创建一个socket
使用socket()
函数来创建一个socket,示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
socket()
用于函数创建socket并且返回一个socket描述符,该描述符可以在其他网络命令中使用,上述代码将会创建像下面这样的socket:
Address Family : AF_INET 表示IPv4
Type : SOCK_STREAM 面向TCP协议的
Protocol : 0 [ or IPPROTO_TCP , IPPROTO_UDP ]
这里here可以获取更多信息
下一步我们可以连接到google.com。
注意 除了SOCK_STREAM 类型以外还有一种类型叫做 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
|
发送接收数据
函数send recv用来发送接收数据。下面的例子我们将发送请求给google.com并且接收返回的数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
|
一下是上面代码的输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
我们可以看到google.com返回的数据,它看起来好像是html,是的那就是html。google返回了我们想要的数据,太简单啦!
现在我们已经收到了我们的数据,现在我们该关掉socket了。
关闭socket
closesocket函数是用来关闭socket的,另外WSACleanup 函数也必须被调用来卸载winsock库ws2_32.dll。
1 2 |
|
.就是这些
由主机名/域名获得ip地址
当要连接到一个远程主机的时候,必须要知道它的iP地址。gethostbyname
就是用来获取ip的。它使用域名作为参数并且返回一个hostent结构体,该结构体包含ip信息。该结构体包含于netdb.h中,结构如下:
注意
gethostbyname 函数已被废弃,取而代之的是getaddrinfo函数。强烈建议winsock2的开发者使用getaddrinfo而不是gethostbyname |
1 2 3 4 5 6 7 8 9 |
|
h_addr_list
包含ip地址,如下代码演示如何获取地址。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
|
代码输出如下
1 |
|
h_addr_list
可以把长地址转换成点分地址。
服务器相关概念
OK现在我们来看一下服务器相关的东西,服务器基本上就做了如下几件事:
1. 打开socket
2. 绑定到一个地址和端口
3. Listen 监听进来的连接
4. Accept 接受连接
5. Read/Send读取数据/发送数据
We have already learnt how to open a socket. So the next thing would be to bind it.
Bind a socket
Function bind
can be used to bind a socket to a particular address and port. It needs a sockaddr_in structure similar to connect function.
Lets see a code example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
|
Now that bind is done, its time to make the socket listen to connections. We bind a socket to a particular IP address and a certain port number. By doing this we ensure that all incoming data which is directed towards this port number is received by this application.
This makes it obvious that you cannot have 2 sockets bound to the same port.
Listen for connections
After binding a socket to a port the next thing we need to do is listen for connections. For this we need to put the socket in listening mode. Function listen
is used to put the socket in listening mode. Just add the following line after bind.
1 2 |
|
Thats all. Now comes the main part of accepting new connections.
Accept connection
Function accept
is used for this. Here is the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
|
Output
Run the program. It should show
1 2 3 4 |
|
So now this program is waiting for incoming connections on port 8888. Dont close this program , keep it running.
Now a client can connect to it on this port. We shall use the telnet client for testing this. Open a terminal and type
1 |
|
And the server output will show
1 2 3 4 5 6 |
|
So we can see that the client connected to the server. Try the above process till you get it perfect.
Note
You can get the ip address of client and the port of connection by using the sockaddr_in structure passed to accept function. It is very simple :
1 2 |
|
We accepted an incoming connection but closed it immediately. This was not very productive. There are lots of things that can be done after an incoming connection is established. Afterall the connection was established for the purpose of communication. So lets reply to the client.
Here is an example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
|
Run the above code in 1 terminal. And connect to this server using telnet from another terminal and you should see this :
1 |
|
So the client(telnet) received a reply from server. We had to use a getchar because otherwise the output would scroll out of the client terminal without waiting
We can see that the connection is closed immediately after that simply because the server program ends after accepting and sending reply. A server like www.google.com is always up to accept incoming connections.
It means that a server is supposed to be running all the time. Afterall its a server meant to serve. So we need to keep our server RUNNING non-stop. The simplest way to do this is to put the accept
in a loop so that it can receive incoming connections all the time.
Live Server
So a live server will be alive for all time. Lets code this up :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
|
We havent done a lot there. Just the accept was put in a loop.
Now run the program in 1 terminal , and open 3 other terminals. From each of the 3 terminal do a telnet to the server port.
Run telnet like this
1 |
|
1 2 3 |
|
1 |
|
And the server terminal would show
1 2 3 4 5 6 |
|
So now the server is running nonstop and the telnet terminals are also connected nonstop. Now close the server program.
All telnet terminals would show "Connection to host lost."
Good so far. But still there is not effective communication between the server and the client.
The server program accepts connections in a loop and just send them a reply, after that it does nothing with them. Also it is not able to handle more than 1 connection at a time. So now its time to handle the connections , and handle multiple connections together.
Handling Connections
To handle every connection we need a separate handling code to run along with the main server accepting connections.
One way to achieve this is using threads. The main server program accepts a connection and creates a new thread to handle communication for the connection, and then the server goes back to accept more connections.
We shall now use threads to create handlers for each connection the server accepts. Lets do it pal.
1 |
Run the above server and open 3 terminals like before. Now the server will create a thread for each client connecting to it.
The telnet terminals would show :
1 |
This one looks good , but the communication handler is also quite dumb. After the greeting it terminates. It should stay alive and keep communicating with the client.
One way to do this is by making the connection handler wait for some message from a client as long as the client is connected. If the client disconnects , the connection handler ends.
So the connection handler can be rewritten like this :
1 |
The above connection handler takes some input from the client and replies back with the same. Simple! Here is how the telnet output might look
1 |
So now we have a server thats communicative. Thats useful now.
Conclusion
The winsock api is quite similar to Linux sockets in terms of function name and structures. Few differences exist like :
1. Winsock needs to be initialised with the WSAStartup function. No such thing in linux.
2. Header file names are different. Winsock needs winsock2.h , whereas Linux needs socket.h , apra/inet.h , unistd.h and many others.
3. Winsock function to close a socket is closesocket
, whereas on Linux it is close
.
On Winsock WSACleanup must also be called to unload the winsock dll.
4. On winsock the error number is fetched by the function WSAGetLastError()
. On Linux the errno variable from errno.h file is filled with the error number.
And there are many more differences as we go deep.
By now you must have learned the basics of socket programming in C. You can try out some experiments like writing a chat client or something similar.
If you think that the tutorial needs some addons or improvements or any of the code snippets above dont work then feel free to make a comment below so that it gets fixed.
Last Updated On : 12th December 2012
socket programmingwinsockwinsock tutorial
Handle multiple connections - Asynchronous socket programming
For this server to be any useful, it must be able to accept multiple incoming connections and keep processing them till the clients want. So the next attempt shall be to write a server that can handle multiple connections and tackle all of them simultaneously.
There are many ways to handle multiple client connections. The first and most intuitive one is using threads. As soon as a client connects, assign a separate thread to process each client. However threads are too much work and difficult to code properly.
There are other techniques like polling. Polling involves monitoring multiple sockets to see if "something" happened on any of them. For example, the server could be monitoring the sockets of 5 connected clients, and as soon as any of them send a message, the server gets notified of the event and then processes it. In this way it can handle multiple sockets. The winsock api provides a function called "select" which can monitor multiple sockets for some activity.
Since we are able to handle all sockets together at once it is called asynchronous socket programming. It is also called event-driven socket programming or select()-based multiplexing.
The select function prototype is like this
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timeval *timeout);
The first parameter is a dummy one. The readfds parameter is a pointer to an array of sockets which should be monitored to be readable. This means that if any socket in the readfds set receives some data, it becomes readable. Similarly the writefds sockets would be monitored to be writable and the exceptfds sockets shall be monitored for any error. The last parameter is the timeout parameter, which indicates the length of time which the select function shall wait for before returning.
Now after a select function returns, it re-fills the same readfds array with the readable sockets. Same with writefds and exceptfds. This means that we have to keep calling select function in a loop, and everytime have to prepare our list of readfds, writefds and exceptfds array of sockets to pass.
The socket arrays are variables of type fd_set. fd_set is basically a structure that looks like this
typedef struct fd_set { u_int fd_count; SOCKET fd_array[FD_SETSIZE]; } fd_set;
To work with fd_set array the following macros have to be used.
FD_CLR(s, *set) - Removes a socket from an fd_set structure FD_ISSET(s, *set) - Checks if a socket is present in an fd_set structure FD_SET(s, *set) - Adds a socket to an fd_set structure FD_ZERO(*set) - Initializes the set to the null set. This will empty an fd_set structure
Now that is a lot of theory. Lets get to the final code that uses all that theory to get something working.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 |
|
Does that look like a big program. Compile and run it. It should show an output like this
Initialising Winsock...Initialised. Socket created. Bind done Waiting for incoming connections...
Now the socket server is ready and waiting for incoming connection. At this point we need to connect to it using some client like telnet. But wait, we are not going to use telnet. Telnet has a problem that it always operates in character mode and that will screw up our interaction with this simple program. So get another utility called putty or ncat. Ncat is the netcat version that comes with nmap. Download it from their website. Or download puttytel , the putty telnet.
If you are using ncat then connect to the socket server like this
C:\>ncat localhost 8888
If you are using puttytel, the launch it and go to Connection > Telnet and select Passive mode. This will make putty line mode. Then come back to Session tab and enter the hostname and port and click open. it will connect to the server and start a black telnet like terminal.
Once the client program is connected with the server, try sending some message by typing first and then hit enter. The server will reply back with the same message.
C:\>ncat localhost 8888 ECHO Daemon v1.0 hello hello how are you how are you i am fine i am fine
The server terminal would look like this
Initialising Winsock...Initialised. Socket created. Bind done Waiting for incoming connections... New connection , socket fd is 3972 , ip is : 127.0.0.1 , port : 1129 Welcome message sent successfully Adding to list of sockets at index 0 127.0.0.1:1129 - hello 127.0.0.1:1129 - how are you 127.0.0.1:1129 - i am fine
And now, try to open multiple client terminals and connect at the same time to server. The server would be able to process requests from all the clients together.
Initialising Winsock...Initialised. Socket created. Bind done Waiting for incoming connections... New connection , socket fd is 3972 , ip is : 127.0.0.1 , port : 1129 Welcome message sent successfully Adding to list of sockets at index 0 127.0.0.1:1129 - hello 127.0.0.1:1129 - how are you 127.0.0.1:1129 - i am fine New connection , socket fd is 3956 , ip is : 127.0.0.1 , port : 1130 Welcome message sent successfully Adding to list of sockets at index 1 127.0.0.1:1130 - i am the second client New connection , socket fd is 3944 , ip is : 127.0.0.1 , port : 1131 Welcome message sent successfully Adding to list of sockets at index 2 127.0.0.1:1131 - and i am the third 127.0.0.1:1131 - ha ha ha
Now thats a long run. I will go and take a cup of coffee, and meanwhile you check if the programs are running fine.
Last Updated On : 28th March 2013
winsock教程- windows下的socket编程(c语言实现),布布扣,bubuko.com