我的客户有问题。我使用线程与服务器建立多个连接。客户端应连接到服务器并相互通信。问题是他们无法连接到服务器。
这是我的代码:
client.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include<pthread.h>
typedef struct{
int portno;
int sockfd;
const char *ip;
const char *username;
}clients;
clients client;
int server_connect()
{
int sock;
struct sockaddr_in server;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1)
{
errx(1, "Could not create socket");
exit(EXIT_FAILURE);
}
memset(&server, 0, sizeof server);
server.sin_addr.s_addr = inet_addr(client.ip);
server.sin_family = AF_INET;
server.sin_port = htons(client.portno);
if (connect(sock, (struct sockaddr *) &server, sizeof(server)) < 0)
{
errx(1, "Connect failed. Error");
exit(EXIT_FAILURE);
}
fprintf(stdout, "Connected to server\n");
client.sockfd = sock;
pthread_t send_thread, receive_thread;
if (pthread_create(&send_thread, NULL, send_message, (void *) &client.sockfd) < 0)
errx (1, "can not create send thread");
if (pthread_create(&receive_thread, NULL, receive_message, (void *) &client.sockfd) < 0)
errx (1, "can not create receive thread");
pthread_join(send_thread, NULL);
pthread_join(receive_thread, NULL);
close(sock);
return 0;
}
send_message()和receive_message()
void *send_message()
{
char buffer[256], log[256];
snprintf(log, sizeof log, "user %s is joined.", client.username);
if (send(client.sockfd, log, sizeof log, 0) < 0)
errx(1, "Send failed");
while (1) {
fprintf(stdout, "%s","> ");
bzero(buffer,256);
fgets(buffer,255,stdin);
if (send(client.sockfd, buffer, sizeof buffer, 0) < 0) {
errx(1, "Send failed");
}
}
}
void *receive_message() {
while (1) {
char server_reply[2000];
if (recv(client.sockfd, server_reply, 2000, 0) < 0) {
errx(1,"recv failed");
}
//Receive a reply from the server
fprintf(stdout, "%s\n", server_reply);
}
}
代码的某些部分不是我的,我通过搜索发现了它。您能帮我发现错误吗?