简体   繁体   English

如何在类中封装C/C++套接字发送和接收函数?

[英]How to encapsulate C/C++ socket send and receive functions in a class?

I'm using the standard C/C++ socket function, but I'd like to encapsulate them into a C++ class.我正在使用标准的 C/C++ 套接字函数,但我想将它们封装到 C++ 类中。 The problem is that the functions for sending and receive returns (or require) pointers to void.问题在于发送和接收函数返回(或要求)指向 void 的指针。 Is there any way to use an object that encapsulates those values?有没有办法使用封装这些值的对象?

For example, in Java the Socket class uses both ObjectOutputStream and ObjectInputStream in order to work with Object type so every object can be sent via Sockets.例如,在 Java 中, Socket类同时使用ObjectOutputStreamObjectInputStream来处理 Object 类型,因此每个对象都可以通过 Sockets 发送。 I know that in Java the approach is quite different because the pointers are hidden to the programmer, but is there any similar solution in C++?我知道在 Java 中这种方法完全不同,因为指针对程序员是隐藏的,但是在 C++ 中是否有类似的解决方案?

socket isn't a c++ function. socket不是 C++ 函数。 It's a system level function and it doesn't know anything about objects (or indeed anything in c++), so you have to arrange to provide it with a pointer to the data you want transferred.它是一个系统级函数,它对对象一无所知(或者实际上是 C++ 中的任何东西),因此您必须安排为它提供指向要传输的数据的指针。

As @GCT says, socket isn't a function but is a system level function which is used to handle network connections.正如@GCT 所说,套接字不是一个函数,而是一个用于处理网络连接的系统级函数。 In C/C++ each socket is identified with an Integer value, so it's not easy, as you want, to handle it as an object.在 C/C++ 中,每个套接字都用一个 Integer 值标识,因此将其作为对象处理并不容易,如您所愿。

I recommend you to read this tutorial to know more about socket.我建议您阅读本 教程以了解有关 socket 的更多信息。

Maybe it can help you: I have a project that show how to use sockets in C++.也许它可以帮助你:我有一个项目展示了如何在 C++ 中使用套接字。 Server and client are contained in their own class.服务器和客户端包含在它们自己的类中。 You can get it by this link .你可以通过这个链接得到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM