C ++通过套接字发送字符串 [英] C++ sending string over socket

查看:84
本文介绍了C ++通过套接字发送字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个小型的客户端/服务器项目,作为C ++课程的最终项目。我们得到了一些用于通信的类(使用sys / socket.h),我们基本上可以执行 connection-> send(byte)来发送一个字节的数据

I'm doing a small client/server project as a final project in a C++ course. We are handed some classes that take care of communication (using sys/socket.h) and we can basically do connection->send(byte) to send one byte of data.

说我有一个要发送的字符串。从客户端发送到服务器时,如何确保将 a解释为 a,反之亦然?由于标准没有说关于默认为未签名或已签名的char的任何信息,所以我不知道如何处理它。

Say I have a string that I want to send. How do I make sure an 'a' is interpreted as an 'a' when sent from client to server or vice versa? Since the standard isn't saying anything about char defaulting to unsigned or signed I don't know how to handle it.

我有一个想法,我可以减去 std :: numeric_limits< char> :: min()在每一端,但我不确定这是一个好方法。

I had some idea that I could subtract std::numeric_limits<char>::min() on each end but I'm not sure it is a good one.

推荐答案

TCP和UDP都不关心字符串的编码。它将始终被解释为字节数组。因此,要确保正确解释您的字符串,服务器和客户端都必须就通用编码达成共识。

Neither TCP nor UDP care about the encoding of your string. It will always be interpreted just as an array of bytes. So to make sure your string is interpreted correctly both server and client have to agree on a common encoding.

在您的情况下,我将简单地使用 c_str()方法,用于发送字符串并通过将接收到的数据解释为 const char * 来分配字符串(对于ASCII字符串)。只要客户端应用程序和服务器应用程序使用相同的字符串库,此方法就应该起作用。

In your case I would simply work with the c_str() method of std::string for sending the string and assigning the string by interpreting received data as const char* (For ASCII strings). This should work as long as the client app and the server app are using the same string libraries.

这篇关于C ++通过套接字发送字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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