老师出了个关于socket编程的问题。帮忙解决!
要求做到用同一个程序,在同一台,或是两台机器之间进行一对一的通信。
但是我现在通过了编译,但是达不到效果,互相之间无法通信。
那位大虾,帮忙看看,我是在美国读EE的,不懂编程,sign..
谢谢!
运行使用,
client_chat jaguar 7777 8888。
要用同一个文件。
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <netdb.h>
#include <pthread.h>
#define MAX_PENDING 5
#define MAX_LINE 256
void *Listen(void *);
int server_port;
int client_port;
int main(int argc, char *argv[])
{
FILE *fp;
struct hostent *hp;
struct sockaddr_in sin;
char *host;
char buf[MAX_LINE];
int s;
int len;
pthread_t tid;
if (argc == 4)
{
host = argv[1];
sscanf(argv[2],"%d",&server_port);
sscanf(argv[3],"%d",&client_port);
}
else
{
fprintf(stderr, "usage: simplex-talk host\n");
exit(1);
}
pthread_create (&tid, NULL, Listen, NULL);
/* translate host name into peer"s IP address */
hp = gethostbyname(host);
if (!hp)
{
fprintf(stderr, "simplex-talk: unknow host: %s\n", host);
exit(1);
}
/* build address data structure */
bzero ((char *)&sin, sizeof(sin));
//memset((char *)&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
bcopy (hp->h_addr, (char *)&sin.sin_addr, hp->h_length);
//sin.sin_addr = * ((LPIN_ADDR)*hp->h_addr_list);
sin.sin_port = htons(client_port);
/* active open */
if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("simplex-talk: socket");
exit(1);
}
while(connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0)
{
// perror("simplex-talk: connect");
// close(s);
// exit(1);
}
/* main loop: get and send lines of text */
while (fgets(buf , sizeof(buf), stdin))
{
buf[MAX_LINE -1] = '\0';
len = strlen(buf) + 1;
send(s, buf, len, 0);
}
close(s);
}
void *
Listen(void *arg)
{
struct sockaddr_in sin;
char buf[MAX_LINE];
int len;
int s, new_s;
bzero ((char *)&sin, sizeof (sin));
//memset((char *)&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(server_port);
/* setup passive open */
if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("simplex-talk: socket");
exit(1);
}
if ((bind(s, (struct sockaddr *)&sin, sizeof(sin))) < 0)
{
perror("simplex-talk: bind");
exit(1);
}
listen(s, MAX_PENDING);
/* wait for connection, then receive and print text */
while (1)
{
if ((new_s = accept(s, NULL, NULL)) < 0)
{
perror("simplex-talk: accept");
exit(1);
}
while (len = recv(new_s, buf, sizeof(buf), 0))
{
if(len == -1)
break;
fputs(buf, stdout);
}
close(new_s);
}
close(s);
}