|
服务端 service.c- #include <stdio.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <netdb.h>
- #include <stdlib.h>
- #include <string.h>
- int port = 17000;
- main ()
- {
- struct sockaddr_in sin;
- struct sockaddr_in pin;
- int sock_descriptor;
- int temp_sock_descriptor;
- int size_of_addr;
- size_of_addr=sizeof(pin);
- char buf[8192];
- int i, lenth;
- sock_descriptor = socket (AF_INET, SOCK_STREAM, 0);
- bzero (&sin, sizeof (sin));
- sin.sin_family = AF_INET;
- sin.sin_addr.s_addr = htonl(INADDR_ANY);
- sin.sin_port = htons (port);
- if (bind (sock_descriptor, (struct sockaddr *) &sin, sizeof (sin)) == -1)
- {
- perror ("bind!"); exit (1);}
- if (listen (sock_descriptor, 20) == -1)
- {
- perror ("listen!"); exit (1);}
- printf ("waiting for accepting connections from client\n");
- while (1)
- {
- temp_sock_descriptor = accept(sock_descriptor,(struct sockaddr *)&pin,&size_of_addr);
- if (temp_sock_descriptor == -1)
- {
- perror ("call to accept"); }
- if (recv (temp_sock_descriptor, buf, sizeof (buf), 0) == -1)
- {
- perror ("recv!"); exit (1);}
- printf ("received:%s\n", buf);
- lenth = strlen (buf);
- for (i = 0; i <= lenth; i++)
- {
- buf[i] = toupper (buf[i]);
- if (send (temp_sock_descriptor, buf, lenth, 0) == -1)
- {
- perror ("send!"); exit (1);}
- }
- close (temp_sock_descriptor);
- }
- }
复制代码 客户端 client.c- #include <stdio.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <netdb.h>
- #include <string.h>
- #include <stdlib.h>
- char * host_name="127.0.0.1";
- int port=17000;
- void main(int argc,char *argv[])
- {
- char buf[4096];
- char message[1024];
- int socket_descriptor;
- struct sockaddr_in pin;
- struct hostent *server_host_name;
- char *message_str="hello,network";
- if(argc<2)
- {printf("send default srting.\n");
- }else{
- message_str=argv[1];
- }
- if((server_host_name=gethostbyname(host_name))==0)
- {
- perror("cant resolving localhost\n");
- exit(1);
- }
- bzero(&pin,sizeof(pin));
- pin.sin_family=AF_INET;
- pin.sin_addr.s_addr=htonl(INADDR_ANY);
- pin.sin_addr.s_addr=((struct in_addr *)(server_host_name->h_addr))->s_addr;
- pin.sin_port=htons(port);
- if((socket_descriptor=socket(AF_INET,SOCK_STREAM,0))==-1)
- {perror("Error opening socket\n");
- exit(1);
- }
- if(connect(socket_descriptor,(void *)&pin,sizeof(pin))==-1)
- {
- perror("cant connecting to server");
- exit(1);
- }
- printf("send message %s to server ...\n",message_str);
- if (send(socket_descriptor,message_str,strlen(message_str),0)==-1)
- {
- perror("cant send message\n");
- exit(1);
- }
- printf("waiting for response from server\n");
- if (recv(socket_descriptor,buf,sizeof(buf),0)==-1)
- {
- perror("cant receive response\n");
- exit(1);
- }
- printf("\nResponse from server:\n\n%s\n",buf);
- close(socket_descriptor);
- }
复制代码 |
|