TCP服务器和客户端示例

TCP服务器和客户端示例

本文介绍了什么是简单的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 ++构建该代码:

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 party库,因为运行此程序的系统非常受限制。这必须是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>

在,将clilen的类型更改为socklen_t。

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

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

在,更改以下行:

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

到:

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


推荐答案

我用过过去。它是用C语言编写的,而不是C ++语言,但是示例很好。直接转到,以获取简单的客户端和服务器示例程序。

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服务器和客户端示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 22:16