有人可以发布一个简单的C或C ++ TCP服务器和客户端示例吗? [英] Could someone post a simple C or C++ TCP server and client example?

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

问题描述

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



我试图使用本教程中的代码,但是我无法在Linux中使用g ++编译: http://www.linuxhowtos.org/C_C++/socket.htm



如果可能,我想避免第三方库,因为我运行这个系统是相当受限制。



由于 emg-2 的答案,我设法使得上述代码示例与C ++兼容,使用以下步骤:



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



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

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

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

client.c ,更改以下行:

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



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


解决方案

我使用了 Beej的网络编程指南。它在C,而不是C ++,但例子是好的。直接访问第6部分,了解简单的客户端和服务器示例程序。


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.

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

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.

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>

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

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

In client.c, change the following line:

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

To:

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

解决方案

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天全站免登陆