服务器为客户端提供字符串检索功能(留供后查)
完整代码请联系送信zhao.QIMI@yahoo.com
server侧代码
//////////////////////////////////////////////////////////////
//author :qi
//date :2019/4
//////////////////////////////////////////////////////////////#include "grepServer.h"
//log used
time_t msgTime;
char errMassage[MG_HAF_MAXLINE];
int main(int argc(), char** argv)
{
//socket used
int socket_fd, connect_fd;
struct sockaddr_in servAddr, clientAddr;
int struct_len;
//Initialization socket
if( (socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
time(&msgTime);
logWrite(__LINE__, &msgTime, errno, MGERR_SOCKET_INIT);
exit(0);
}#ifdef MG_DEBUG
// debug trace
time(&msgTime);
sprintf(errMassage, "*************debug start**************");
logWrite(__LINE__, &msgTime, errno, errMassage);
#endifmemset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(MG_DEFALUT_PORT);
bzero(&(servAddr.sin_zero), 8);
struct_len = sizeof(struct sockaddr_in);if( bind(socket_fd, (struct sockaddr*)&servAddr, sizeof(servAddr)) == -1)
{
time(&msgTime);
logWrite(__LINE__, &msgTime, errno, MGERR_SOCKET_BIND);
exit(0);
}if( listen(socket_fd, 10) == -1)
{
time(&msgTime);
logWrite(__LINE__, &msgTime, errno, MGERR_SOCKET_LISTEN);
exit(0);
}//write server start time.
time(&msgTime);
logWrite(__LINE__, &msgTime, 0, MGERR_SOCKET_SUCCESS);// manage client request
while(1)
{
pthread_t thread;
if( (connect_fd = accept(socket_fd, (struct sockaddr*)&clientAddr, &struct_len)) == -1)
{
//printf("sockeip=%s,port=%d,connect_fd=%d.", inet_ntoa(clientAddr.sin_addr), clientAddr.sin_port, connect_fd);
time(&msgTime);
logWrite(__LINE__, &msgTime, errno, MGERR_MSG_RECV);
exit(0);
}#ifdef MG_DEBUG
// debug trace
time(&msgTime);
sprintf(errMassage, "connect success! connect_fd = %d", connect_fd);
logWrite(__LINE__, &msgTime, errno, errMassage);
#endif
// create child thread
if(0 != pthread_create(&thread, NULL, mg_rec_data, (void*)(&connect_fd)))
{
time(&msgTime);
logWrite(__LINE__, &msgTime, errno, MGERR_CHILD_CREATE);
exit(0);
}
}
exit(0);
}////////////////////////////////////////
// child thread to handle client data
// connect_fd: socket handle
////////////////////////////////////////
void *mg_rec_data(void *fd)
{
int connect_fd;
_MG_MSG_CTS cts_rcv_data; //recv data
_MG_M

这是一个使用C语言在Linux环境下实现的TCP多线程Socket服务器和客户端的简单示例。服务器监听指定端口,接收客户端连接,并在接收到请求后搜索文件中包含特定字符串的行并返回给客户端。客户端发送查找字符串和源文件名到服务器,然后接收并处理服务器返回的数据。
最低0.47元/天 解锁文章
2097

被折叠的 条评论
为什么被折叠?



