多个线程写入同一个套接字导致问题 [英] Multiple threads writing to same socket causing issues

查看:59
本文介绍了多个线程写入同一个套接字导致问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个客户端/服务器应用程序,其中服务器根据来自客户端的请求生成多个线程.

I have written a client/server application where the server spawns multiple threads depending upon the request from client.

这些线程应该向客户端发送一些数据(字符串).

These threads are expected to send some data to the client(string).

问题是,数据在客户端被覆盖.我该如何解决这个问题?

The problem is, data gets overwritten on the client side. How do I tackle this issue ?

我已经阅读了一些关于类似问题的其他主题,但无法找到确切的解决方案.

I have already read some other threads on similar issue but unable to find the exact solution.

这是我接收数据的客户端代码.

Here is my client code to receive data.

while(1)
    {
            char buff[MAX_BUFF];
            int bytes_read = read(sd,buff,MAX_BUFF);
            if(bytes_read == 0)
            {
                    break;
            }
            else if(bytes_read > 0)
            {
                    if(buff[bytes_read-1]=='$')
                    {
                            buff[bytes_read-1]='\0';
                            cout<<buff;
                    }
                    else
                    {
                            cout<<buff;
                    }
            }
    }

服务器线程代码:

void send_data(int sd,char *data)
{
    write(sd,data,strlen(data));
    cout<<data;
}

void *calcWordCount(void *arg)
{
    tdata *tmp = (tdata *)arg;
    string line = tmp->line;
    string s = tmp->arg;
    int sd = tmp->sd_c;
    int line_no = tmp->line_no;
    int startpos = 0;
    int finds = 0;
    while ((startpos = line.find(s, startpos)) != std::string::npos)
    {
            ++finds;
            startpos+=1;
            pthread_mutex_lock(&myMux);
            tcount++;
            pthread_mutex_unlock(&myMux);
    }
    pthread_mutex_lock(&mapMux);
    int t=wcount[s];
    wcount[s]=t+finds;
    pthread_mutex_unlock(&mapMux);


    char buff[MAX_BUFF];
    sprintf(buff,"%s",s.c_str());
    sprintf(buff+strlen(buff),"%s"," occured ");
    sprintf(buff+strlen(buff),"%d",finds);
    sprintf(buff+strlen(buff),"%s"," times on line ");
    sprintf(buff+strlen(buff),"%d",line_no);
    sprintf(buff+strlen(buff),"\n",strlen("\n"));
    send_data(sd,buff);
    delete (tdata*)arg;
}

推荐答案

  1. 在服务器端,确保共享资源(套接字及其关联的内部缓冲区)受到保护,防止并发访问.
  2. 定义并实现服务器使用的应用级协议,使客户端能够区分不同线程发送的内容.

附加说明: 不能依赖 read()/write() 读/写与这两个函数一样多的字节被告知读/写.检查它们的返回值以了解这些函数实际读取/写入的字节数并循环它们直到所有要读取/写入的数据都被读取/写入是必不可少的.

As an additional note: One cannot rely on read()/write() reading/writing as much bytes as those two functions were told to read/write. It is an essential necessity to check their return value to learn how much bytes those functions actually read/wrote and loop around them until all data that was intended to be read/written had been read/written.

这篇关于多个线程写入同一个套接字导致问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆