CLIENT:
1. 调用socket函数create一个(int)socket:
clientsock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)
2. 初始化一个(struct sockaddr_in)echoserver:
memset(&echoserver, 0, sizeof(echoserver));
echoserver.sin_family = AF_INET;
echoserver.sin_port = htons(atoi(argv[3])); //Server Port
echoserver.sin_addr.s_addr = inet_addr(argv[1]); //Server IP
3. 调用connet向server发起连接请求:
connect(clientsock,&echoserver,sizeof(echoserver);
4. 调用send向已经与server连接的socket发数据
send(clientsock, argv[2], echolenth, 0)
5. 或调用recv从已经与server连接的socket接收数据
recv(clientsock,buffer,BUFFER_SIZE-1,0)
6. 用完关闭socket
close(clientsock)
SERVER:
1. create (int)socket-serversock(for bind/listen/accept), define clientsock(for recv):
serversock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)
2. 初始化(struct sockaddr_in)echoserver(for bind),定义echoclient(for accept):
memset(&echoserver, 0, sizeof(echoserver)); /* Clear struct */
echoserver.sin_family = AF_INET; /* Internet/IP */
echoserver.sin_addr.s_addr = htonl(INADDR_ANY); /* Incoming addr */
echoserver.sin_port = htons(atoi(argv[1])); /* server port */
3. 调用bind绑定echoserver:
bind(serversock, &echoserver, sizeof(echoserver));
4. 监听端口
listen(serversock, MAXPENDING) /*可设置最大连接数*/
5. while循环里等待连接请求
/*得到(int)clientsock,(struct sockaddr_in)echoclient的信息*/
(int)clientsock = accept(serversock, &echoclient, &length/*sizeof(echoclient)*/)
6. 处理接收到的clientsock
6.1 从clientsock中接收数据:
recv(clientsock,buffer,BUFFSIZE,0)
6.2 往clientsock中发送数据:
send(clientsock, buffer, received, 0)
6.3 关闭clientsock:
close(clientsock);
参考:
http://www.ibm.com/developerworks/cn/views/linux/tutorials.jsp?cv_doc_id=85074
11/17/2007
订阅:
博文评论 (Atom)
没有评论:
发表评论