当前位置: 技术问答>linux和unix
linux 下socket编程,可以互相链接但是无法发送数据,请各位大侠帮忙看看
来源: 互联网 发布时间:2017-03-25
本文导语: 只是想实现简单的俩台电脑通信: 服务器端: #include #include #include #include #include #include #include #include #define SERVPORT 3333 #define MAXDATASIZE 100 #define SERVER_IP "127.0.0.1" #define DATA "this is a client message" int ...
只是想实现简单的俩台电脑通信:
服务器端:
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVPORT 3333
#define MAXDATASIZE 100
#define SERVER_IP "127.0.0.1"
#define DATA "this is a client message"
int main(int argc, char* argv[]) {
int sockfd, recvbytes;
char buf[MAXDATASIZE];
struct hostent *host;
struct sockaddr_in serv_addr;
if (( sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket error!");
exit(1);
}
bzero(&serv_addr,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERVPORT);
serv_addr.sin_addr.s_addr= inet_addr(SERVER_IP);
if (connect(sockfd, (struct sockaddr *)&serv_addr,sizeof(struct sockaddr)) == -1) {
perror("connect error!");
exit(1);
}
write(sockfd,DATA, sizeof(DATA));
if ((recvbytes = recv(sockfd, buf, MAXDATASIZE,0)) == -1) {
perror("recv error!");
exit(1);
}
buf[recvbytes] = '';
printf("Received: %s",buf);
close(sockfd);
return 0;
}
客户端没有问题吧:
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
int server_sockfd;
int client_sockfd;
int len;
struct sockaddr_in my_addr;
struct sockaddr_in remote_addr;
int sin_size;
char buf[BUFSIZ];
memset(&my_addr,0,sizeof(my_addr));
my_addr.sin_family=AF_INET;
my_addr.sin_addr.s_addr=INADDR_ANY;
my_addr.sin_port=htons(8000);
if((server_sockfd=socket(PF_INET,SOCK_STREAM,0))
服务器端:
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVPORT 3333
#define MAXDATASIZE 100
#define SERVER_IP "127.0.0.1"
#define DATA "this is a client message"
int main(int argc, char* argv[]) {
int sockfd, recvbytes;
char buf[MAXDATASIZE];
struct hostent *host;
struct sockaddr_in serv_addr;
if (( sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket error!");
exit(1);
}
bzero(&serv_addr,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERVPORT);
serv_addr.sin_addr.s_addr= inet_addr(SERVER_IP);
if (connect(sockfd, (struct sockaddr *)&serv_addr,sizeof(struct sockaddr)) == -1) {
perror("connect error!");
exit(1);
}
write(sockfd,DATA, sizeof(DATA));
if ((recvbytes = recv(sockfd, buf, MAXDATASIZE,0)) == -1) {
perror("recv error!");
exit(1);
}
buf[recvbytes] = '';
printf("Received: %s",buf);
close(sockfd);
return 0;
}
客户端没有问题吧:
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
int server_sockfd;
int client_sockfd;
int len;
struct sockaddr_in my_addr;
struct sockaddr_in remote_addr;
int sin_size;
char buf[BUFSIZ];
memset(&my_addr,0,sizeof(my_addr));
my_addr.sin_family=AF_INET;
my_addr.sin_addr.s_addr=INADDR_ANY;
my_addr.sin_port=htons(8000);
if((server_sockfd=socket(PF_INET,SOCK_STREAM,0))