什么是简单的 C 或 C++ TCP 服务器和客户端示例? [英] What is a simple C or C++ TCP server and client example?

查看:28
本文介绍了什么是简单的 C 或 C++ TCP 服务器和客户端示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要快速实现一个非常小的 C 或 C++ TCP 服务器/客户端解决方案.这只是将字节数组从一台计算机传输到另一台计算机 - 不需要可扩展/过于复杂.越简单越好.如果可以的话,又快又脏.

I need to quickly implement a very small C or C++ TCP server/client solution. This is simply to transfer literally an array of bytes from one computer to another - doesn't need to be scalable / over-complicated. The simpler the better. Quick and dirty if you can.

我尝试使用本教程中的代码,但无法在 Linux 中使用 g++ 构建它:http://www.linuxhowtos.org/C_C++/socket.htm

I tried to use the code from this tutorial, but I couldn't get it to build using g++ in Linux: http://www.linuxhowtos.org/C_C++/socket.htm

如果可能,我想避免使用 3rd 方库,因为我运行它的系统受到很大限制.这必须是 C 或 C++,因为现有应用程序已经实现.

If possible, I'd like to avoid 3rd party libraries, as the system I'm running this on is quite restricted. This must be C or C++ as the existing application is already implemented.

感谢 emg-2 的回答,我使用以下步骤使上述代码示例与 C++ 兼容:

Thanks to emg-2's answer, I managed to make the above mentioned code sample compatible with C++ using the following steps:

将这些标头添加到客户端和服务器:

Add these headers to both client and server:

#include <cstdlib>
#include <cstring>
#include <unistd.h>

server.c 中,将 clilen 的类型更改为 socklen_t.

In server.c, change the type of clilen to socklen_t.

int sockfd, newsockfd, portno/*, clilen*/;
socklen_t clilen;

client.c 中,更改以下行:

In client.c, change the following line:

if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0) { ... }

致:

if (connect(sockfd,(const sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)

推荐答案

我用过 Beej's过去的网络编程指南.它是用 C 语言编写的,而不是 C++,但是例子很好.直接转到第 6 节,了解简单的客户端和服务器示例程序.

I've used Beej's Guide to Network Programming in the past. It's in C, not C++, but the examples are good. Go directly to section 6 for the simple client and server example programs.

这篇关于什么是简单的 C 或 C++ TCP 服务器和客户端示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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