socket 编程 服务器端-客户端

Posted 魄灆

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket 编程 服务器端-客户端相关的知识,希望对你有一定的参考价值。

/****

服务器端代码

*****/

#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#define PORT 3339
int main(void)
{
char *sendbuf = "thanks";
char buf[256];
int s_fd, c_fd;
int s_len, c_len;
struct sockaddr_in s_addr;
struct sockaddr_in c_addr;
s_fd = socket(AF_INET, SOCK_STREAM, 0);
s_addr.sin_family = AF_INET;
s_addr.sin_addr.s_addr = htonl(INADDR_ANY);
s_addr.sin_port = PORT;
s_len = sizeof(s_addr);
bind(s_fd, (struct sockaddr *)&s_addr,s_len);
listen(s_fd, 10);
while(1)
{
printf("please wait a moment");
c_len = sizeof(c_addr);
c_fd = accept(s_fd,(struct sockaddr *)&c_addr, (socklen_t*__restrict)&c_len);
recv(c_fd,buf,256,0);
buf[sizeof(buf)+1] = ‘\0‘;
printf("receive message:\n%s\n",buf);
send(c_fd, sendbuf, sizeof(sendbuf),0);
close(c_fd);
}
return 0;
}

/*****

客户端代码

****/

#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#define PORT 3339
int main(void)
{
int sockfd;
int len;
struct sockaddr_in addr;
int newsockfd;
char *buf = "come on!";
int len2;
char rebuf[40];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = PORT;
len = sizeof(addr);
newsockfd = connect(sockfd,(struct sockaddr *)&addr, len);
if(newsockfd == -1)
{
perror("link failed!");
return 1;
}
len2 = sizeof(buf);
send(sockfd, buf, len2, 0);
sleep(10);
recv(sockfd, rebuf, 256, 0);
rebuf[sizeof(rebuf) + 1] = ‘\0‘;
printf("receive message :\n%s\n", rebuf);
close(sockfd);
return 0;
}






































































以上是关于socket 编程 服务器端-客户端的主要内容,如果未能解决你的问题,请参考以下文章

11.网络编程:socket服务端客户端

python socket编程之客户端和服务端简单交互

socket编程之TCP/UDP

socket 编程中。 服务端用到多线程

socket编程中,服务器如何检测到客户端网络连接的断开.比如说客户端的网线断掉了,从服务端如何能检测到呢l

基于TCP的客户端服务器端socket编程