- 爱易网页
-
Linux
- linux 上socket编程,可以互相链接但是无法发送数据,请各位大侠帮忙看看
日期:2014-05-16 浏览次数:20773 次
linux 下socket编程,可以互相链接但是无法发送数据,请各位大侠帮忙看看
只是想实现简单的俩台电脑通信:
服务器端:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#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] = '\0';
??? printf("Received: %s",buf);
??? close(sockfd);
??? return 0;
}
客户端没有问题吧:
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
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))<0)
{
perror("创建套接字失败!\n");
return 1;
}
if(bind(server_sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))<0)
{
perror("绑定失败!\n");
return 1;
}
listen(server_sockfd,5);
sin_size=sizeof(struct sockaddr_in);
if(client_sockfd=accept(server_sockfd,(struct sockaddr *)&remote_addr,&sin_size)<0)
{
perror("未收到请求!\n");
return 1;
}
//printf("客户: %s\n",inet_ntoa(remote_addr.sin_addr));
len=send(client_sockfd,"hello!\n",6,0);
while((len=recv(client_sockfd,buf,BUFSIZ,0))>0)
{
buf[len]='\0';
printf("%s\n",buf);
if(send(client_sockfd,buf,len,0)<0)
{
perror("write");
return 1;
}
}
close(client_sockfd);
close(server_sockfd);
return 0;
}
------解决方案--------------------
注意优先级!