C语言使用socket套接字创建聊天,双方能互发消息的源码
时间: 2023-04-04 11:00:48 浏览: 94
以下是使用socket套接字创建聊天,双方能互发消息的C语言源码:
// 服务器端代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 8888
int main()
{
int sockfd, newsockfd, clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
sockfd = socket(AF_INET, SOCK_STREAM, );
if (sockfd < ) {
perror("ERROR opening socket");
exit(1);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(PORT);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < ) {
perror("ERROR on binding");
exit(1);
}
listen(sockfd, 5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < ) {
perror("ERROR on accept");
exit(1);
}
while (1) {
bzero(buffer, 256);
n = read(newsockfd, buffer, 255);
if (n < ) {
perror("ERROR reading from socket");
exit(1);
}
printf("Client: %s\n", buffer);
bzero(buffer, 256);
fgets(buffer, 255, stdin);
n = write(newsockfd, buffer, strlen(buffer));
if (n < ) {
perror("ERROR writing to socket");
exit(1);
}
}
close(newsockfd);
close(sockfd);
return ;
}
// 客户端代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define PORT 8888
int main(int argc, char *argv[])
{
int sockfd, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc < 2) {
fprintf(stderr,"usage %s hostname\n", argv[]);
exit();
}
sockfd = socket(AF_INET, SOCK_STREAM, );
if (sockfd < ) {
perror("ERROR opening socket");
exit(1);
}
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit();
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(PORT);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < ) {
perror("ERROR connecting");
exit(1);
}
while (1) {
bzero(buffer, 256);
fgets(buffer, 255, stdin);
n = write(sockfd, buffer, strlen(buffer));
if (n < ) {
perror("ERROR writing to socket");
exit(1);
}
bzero(buffer, 256);
n = read(sockfd, buffer, 255);
if (n < ) {
perror("ERROR reading from socket");
exit(1);
}
printf("Server: %s\n", buffer);
}
close(sockfd);
return ;
}
阅读全文