1、LinuxSocket编程实例(一个HelloWorld程序)在Linux下写了个小的socket程序,分为客户端和服务器端,服务端开一个端口(2000),做为一个daemon,等待客户的连接请求.一旦有客户连接,服务器端打印出客户端的IP地址和端口,并且向服务器端发送欢迎信息和时间.下面是服务端的代码(tcpserver.c).由于这只是个简单的程序,所以只用了单线程实现!Cpp代码1./** 2. * Tcp Server program, It is a simple example only. 3. * zhengsh 200520602061 2 4
2、. * when client connect to server, send a welcome message and timestamp in server. 5. */ 6. 7.#include 8.#include 9.#include 10.#include 11.#include 12.#include 13.#include 14. 15.#defin
3、e SERVER_PORT 20000 // define the defualt connect port id 16.#define LENGTH_OF_LISTEN_QUEUE 10 //length of listen queue in server 17.#define BUFFER_SIZE 255 18.#define WELCOME_MESSAGE "welcome to connect the server. " 19. 20. 21.int main(int argc, char **argv) 22.{ 23.
5、 4. servaddr.sin_family = AF_INET; 5. servaddr.sin_port = htons(SERVER_PORT); 6. servaddr.sin_addr.s_addr = htons(INADDR_ANY); 7. 8. if (bind(servfd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) 9. { 10. printf("bind to port %d f
6、ailure!",SERVER_PORT); 11. exit(1); 12. } 13. 14. if (listen(servfd,LENGTH_OF_LISTEN_QUEUE) < 0) 15. { 16. printf("call listen failure!"); 17. exit(1); 18. } 19. 20. while (1) 21. {//server l
7、oop will nerver exit unless any body kill the process 22. char buf[BUFFER_SIZE]; 23. long timestamp; 24. socklen_t length = sizeof(cliaddr); 25. clifd = accept(servfd,(struct sockaddr*)&cliaddr,&length); 26. if (c