给我提供一个简单的socket聊天室c程序
时间: 2023-03-16 17:43:49 浏览: 62
我可以为你提供一个简单的Socket聊天室C程序:
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>#define PORT 8080int main(){
int sockfd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = "Hello from the server!";
// Creating socket file descriptor
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("Socket failed");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// Attaching socket to the port
if (bind(sockfd, (struct sockaddr *)&address, sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
} // Listening for connections
if (listen(sockfd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
} // Accepting incoming connection
if ((new_socket = accept(sockfd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
} // Reading message from client
int valread = read( new_socket , buffer, 1024);
printf("%s\n",buffer );
send(new_socket , hello , strlen(hello) , 0 );
printf("Hello message sent\n");
return 0;
}