linux搭建聊天服务器
/*服务器*/
#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 5555
#define BACKLOG 10
#define MAX(a,b) ((a)>(b)?(a):(b))
void str_echo(int);
void server()
{
int sockfd,client_fd;
struct sockaddr_in my_addr;
struct sockaddr_in remote_addr;
socklen_t sin_size;
if((sockfd=socket(AF_INET,SOCK_STREAM,0))== -1)
{
perror("socket create error!");
exit(1);
}
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr=INADDR_ANY;
bzero(&(my_addr.sin_zero),8);
if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1)
{
perror("bind error!");
exit(1);
}
if(listen(sockfd,BACKLOG)==-1)
{
perror("listen error!");
exit(1);
}
while(1)
{
sin_size=sizeof(struct sockaddr_in);
if((client_fd=accept(sockfd,(struct sockaddr *)&remote_addr,&sin_size))==-1)
{
perror("accept error!");
continue;
}
printf("received a connection from %s\n",inet_ntoa(remote_addr.sin_addr));
if(!fork())
{
close(sockfd);
str_echo(client_fd);
exit(0);
}
close(client_fd);
}
}
void str_echo(int sockfd)
{
int maxfd;
char sendbuf[1024]={0};
char recvbuf[1024]={0};
fd_set rfds;
while(1)
{
FD_SET(0,&rfds);
FD_SET(sockfd,&rfds);
maxfd=MAX(0,sockfd)+1;
select(maxfd,&rfds,NULL,NULL,NULL);
if(FD_ISSET(sockfd,&rfds))
{
bzero(recvbuf,1024);
recv(sockfd,recvbuf,1024,0);
printf("C:%s\n",recvbuf);
}
if(FD_ISSET(0,&rfds))
{
read(0,sendbuf,1024);
send(sockfd,sendbuf,strlen(sendbuf),0);
bzero(sendbuf,1024);
}
}
}
int main()
{
server();
return 0;
}
/*客户端*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define SERVPORT 5555
#define MAXSIZE 1024
#define MAX(a,b) ((a)>(b)?(a):(b))
void client(int argc,char **argv)
{
int sockfd,maxfd;
char sendbuf[MAXSIZE]={0};
char recvbuf[MAXSIZE]={0};
// struct hostent *host;
struct sockaddr_in serv_addr;
fd_set rfds;
/* if(argc<2)
{
fprintf(stderr,"Please enter the sserver's name!\n");
exit(1);
}
if((host=gethostbyname(argv[1]))==NULL)
{
herror("get host by name error!\n");
exit(1);
}
*/
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket creat error!\n");
exit(1);
}
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(SERVPORT);
// serv_addr.sin_addr=*((struct in_addr *)host->h_addr);
serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
bzero(&(serv_addr.sin_zero),8);
if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr))==-1)
{
perror("connection error!\n");
exit(1);
}
FD_ZERO(&rfds);
while(1)
{
FD_SET(0,&rfds);
FD_SET(sockfd,&rfds);
maxfd=MAX(0,sockfd)+1;
select(maxfd,&rfds,NULL,NULL,NULL);
if(FD_ISSET(sockfd,&rfds))
{
bzero(recvbuf,MAXSIZE);
recv(sockfd,recvbuf,MAXSIZE,0);
printf("S:%s\n",recvbuf);
}
if(FD_ISSET(0,&rfds))
{
fgets(sendbuf,MAXSIZE,stdin);
send(sockfd,sendbuf,strlen(sendbuf),0);
bzero(sendbuf,MAXSIZE);
}
}
// close(sockfd);
}
int main(int argc,char **argv)
{
client(argc,argv);
return 0;
}
❷ 如何编写linux聊天室
自从开始学linux网络编程后就想写个聊天室,一开始原本打算用多进程的方式来写,可是发觉进程间的通信有点麻烦,而且开销也大,后来想用多线程能不能实现呢,于是便去看了一下linux里线程的用法,实际上只需要知道 pthread_create 就差不多了,于是动手开干,用了两天时间,调试的过程挺痛苦的,一开始打算用纯C来撸,便用简单的数组来存储客户端的连接信息,可是运行时出现了一些很奇怪的问题,不知道是不是访问了临界资源,和线程间的互斥有关等等;奇怪的是,当改用STL的set或map时问题就解决了,但上网搜了下发现STL也不是线程安全的,至于到底是什么问题暂时不想去纠结了,可能是其它一些小细节的错误吧。先贴上代码:
首先是必要的头文件 header.h:
#!/usr/bin/env python#-*- coding: utf-8 -*-from PyQt4 import QtGui, QtCoreimport sysimport socketimport threadclass Client(QtGui.QWidget):
BUF_LEN = 1024 def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setWindowTitle(u'TCP客户端')
self.resize(600, 500)
self.center()
layout = QtGui.QGridLayout(self)
label_ip = QtGui.QLabel(u'远程主机IP:')
layout.addWidget(label_ip, 0, 0, 1, 1)
self.txt_ip = QtGui.QLineEdit('127.0.0.1')
layout.addWidget(self.txt_ip, 0, 1, 1, 3)
label_port = QtGui.QLabel(u'端口:')
layout.addWidget(label_port, 0, 4, 1, 1)
self.txt_port = QtGui.QLineEdit('9003')
layout.addWidget(self.txt_port, 0, 5, 1, 3)
self.isConnected = False
self.btn_connect = QtGui.QPushButton(u'连接')
self.connect(self.btn_connect, QtCore.SIGNAL( 'clicked()'), self.myConnect)
layout.addWidget(self.btn_connect, 0, 8, 1, 2)
label_recvMessage = QtGui.QLabel(u'消息内容:')
layout.addWidget(label_recvMessage, 1, 0, 1, 1)
self.btn_clearRecvMessage = QtGui.QPushButton(u'↓ 清空消息框')
self.connect(self.btn_clearRecvMessage, QtCore.SIGNAL( 'clicked()'), self.myClearRecvMessage)
layout.addWidget(self.btn_clearRecvMessage, 1, 7, 1, 3)
self.txt_recvMessage = QtGui.QTextEdit()
self.txt_recvMessage.setReadOnly(True)
self.txt_recvMessage.setStyleSheet('background-color:yellow')
layout.addWidget(self.txt_recvMessage, 2, 0, 1, 10)
lable_name = QtGui.QLabel(u'姓名(ID):')
layout.addWidget(lable_name, 3, 0, 1, 1)
self.txt_name = QtGui.QLineEdit()
layout.addWidget(self.txt_name, 3, 1, 1, 3)
self.isSendName = QtGui.QRadioButton(u'发送姓名')
self.isSendName.setChecked(False)
layout.addWidget(self.isSendName, 3, 4, 1, 1)
label_sendMessage = QtGui.QLabel(u' 输入框:')
layout.addWidget(label_sendMessage, 4, 0, 1, 1)
self.txt_sendMessage = QtGui.QLineEdit()
self.txt_sendMessage.setStyleSheet("background-color:cyan")
layout.addWidget(self.txt_sendMessage, 4, 1, 1, 7)
self.btn_send = QtGui.QPushButton(u'发送')
self.connect(self.btn_send, QtCore.SIGNAL('clicked()'), self.mySend)
layout.addWidget(self.btn_send, 4, 8, 1, 2)
self.btn_clearSendMessage = QtGui.QPushButton(u'↑ 清空输入框')
self.connect(self.btn_clearSendMessage, QtCore.SIGNAL( 'clicked()'), self.myClearSendMessage)
layout.addWidget(self.btn_clearSendMessage, 5, 6, 1, 2)
self.btn_quit = QtGui.QPushButton(u'退出')
self.connect(self.btn_quit, QtCore.