C语言套接字编程accept()
好吧,我是套接字编程的新手,我的程序的行为并不像我预期的那样。在我看到的套接字编程的所有示例中,它们都使用accept(),并且之后的所有代码都假设已建立连接。
但是一旦我启动服务器,我的accept()就会被调用。这应该发生吗?或者服务器是否应该在执行程序的其余部分之前等待连接?
编辑:哎呀我忘了提及它是一个 TCP 连接。
Okay I'm brand new to socket programming and my program is not behaving like I'd expect it to. In all the examples that I see of socket programming they use accept() and all the code after assumes that a connection has been made.
But my accept() is called as soon as I start the server. Is this supposed to happen? Or is the server supposed to wait for a connection before executing the rest of the program?
EDIT: Oops I forgot to mention it is a TCP connection.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想这就是你所追求的。
http://www.sockets.com/winsock.htm#Accept
中的主要概念winsocket 编程是指您正在使用阻塞或非阻塞套接字。大多数情况下,如果您使用阻塞套接字,您可以查询套接字接收集,以查看是否有任何调用会导致您对例程的调用被阻塞。
从这个 UDP 开始,考虑到它是一个数据报协议,会更容易。另一方面,TCP 是一种流协议。因此,更容易考虑发送和接收的数据块。
I think this is what you're after.
http://www.sockets.com/winsock.htm#Accept
The main concept within winsocket programming is you're working with either blocking or non blocking sockets. Most of the time if you're using blocking sockets you can query the sockets recieve set to see if any call would result in your call to the routine being blocked..
For starting off with this UDP is easier considering its a datagram protocol. TCP on the other hand is a streaming protocol. So it's easier to think in regards to blocks of data that is sent and received.
对于服务器,您:
socket()
。从您的描述中并不清楚您是否正在执行所有这些步骤。
“处理它们”阶段有多个选项,具体取决于您是否计划让单线程单进程在处理下一个请求之前处理一个请求,还是计划让一个多线程进程处理下一个请求。单个进程,其中一个线程接受请求并创建其他线程来执行处理(同时一个线程等待下一个传入连接),或者您是否计划让进程分叉,让子进程在父进程返回时处理新请求监听下一个请求。
For a server, you:
socket()
.It is not clear from your description whether you are doing all those steps.
There are multiple options for the 'process them' phase, depending on whether you plan to have a single-threaded single process handle one request before processing the next, or whether you plan to have a multi-threaded single process, with one thread accepting requests and creating other threads to do the processing (while the one thread waits for the next incoming connection), or whether you plan to have the process fork with the child processing the new request while the parent goes back to listening for the next request.
在开始监听连接后,您应该进入接受循环。使用
select()
检测挂起的客户端连接何时准备好接受,然后调用accept()
接受它。You are supposed to enter your acceptance loop after you have started listening for connections. Use
select()
to detect when a pending client connection is ready to be accepted, then callaccept()
to accept it.