简单的tcp通讯例子。
server端
/* tcp_server.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define MYPORT 8000
int main()
{
int server_fd, client_fd;
struct sockaddr_in my_addr, client_addr;
server_fd = socket(AF_INET, SOCK_STREAM, 0);
my_addr.sin_family = AF_INET; /* 主机字节序 */
my_addr.sin_port = htons(MYPORT); /* short, 网络字节序 */
my_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
bzero(&(my_addr.sin_zero), 8); /* zero the rest of the struct */
bind(server_fd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
listen(server_fd, 10);
while (1) {
char buf[20];
printf("server is waiting\n");
int client_len = sizeof(struct sockaddr);
client_fd = accept(server_fd, (struct sockaddr*)&client_addr, &client_len);
printf("accepted\n");
int n = recv(client_fd, buf, 20, 0);
printf("received from client %s\n", buf);
for (int i=0; i<n; i++) {
if (buf[i]>=97 && buf[i]<=122) {
buf[i] -= 32;
}
}
send(client_fd, buf, 20, 0);
close(client_fd);
}
close(server_fd);
return 0;
}
client端
/* tcp_client.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main()
{
int client_fd;
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8000);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
bzero(&(server_addr.sin_zero), 8);
client_fd = socket(AF_INET, SOCK_STREAM, 0);
connect(client_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
send(client_fd, "hello\0", 6, 0);
char buf[20];
bzero(buf, 20);
recv(client_fd, buf, sizeof(buf), 0);
printf("recv %s\n", buf);
close(client_fd);
return 0;
}
分享到:
相关推荐
基恩士上位机TCP通讯协议,有了这份协议就可以实现上位机TCP协议和基恩士PLC直接通信,不需要购买其他软件了!数据结构简单清晰,一目了然。
三菱 PLC实现MODUBUS TCP 通讯
TCP通讯简单实例,包含服务端(server)与客户端(client)的源程序,推荐编译环境:Microsoft visual stuio 2012(2010)。
三菱 Q 系列 PLC 的 modbusTCP 通讯 三菱 Q 系列 PLC 的 modbusTCP 通讯
基恩士上位机TCP通讯协议,有了这份协议就可以实现上位机TCP协议和基恩士PLC直接通信,不需要购买其他软件了!数据结构简单清晰,一目了然。
易语言源码易语言TCP通讯类源码.rar
该程序是基于winsock实现的TCP客户端/服务器通讯
自己做的一个简单tcp通讯demo,里面包含客户端 服务端。
vb.net&C#和PLC通过Modbus——TCP通讯代码;PC通过Modbus_TCP和PLC进行通讯,简单稳定
WPF上位机,简单实现使用ModBusTcp协议与PLC通讯,读写寄存器功能,内含所有通讯协议解说PDF资料文件
Labview通讯三菱Q PLC,Labvew TCP通讯三菱PLC ,MCTCP,三菱PLC连接LabVIEW,LabVIEW和三菱PLC 通讯 三菱官方MC协议,简单方便,完胜OPC协议。 ,源码开放。 1.支持bool读写 2.支持浮点数读写 3支持 I32读写 4....
C# TCP通讯 制作简易的客户端以及服务器
使用Tcp实现的简单通讯程序,可以拿来当做自己开始学习Qt网络编程的基础
使用C#编写的TCP简单通讯程序
项目要求是要达到即时通讯,群聊和私聊都可以,可以发文件,登陆,注册。可以理解为超级简易的QQ。原理就是获取你的IPV4地址,利用TCP协议通讯发送消息,文件传输用的是udp。
该项目实现了一个简单的 TCP 客户端和服务器通讯系统。 该压缩文件内包含了以下内容: TCP 通讯系统的 Python 代码文件 图形化用户界面(GUI)的代码文件 这个项目的代码经过优化和测试,具有良好的可用性和稳定...
用vb.net实现的TCP IP通讯。简单易用,可靠性高.
简单的TCP客户端与服务器通信程序
TCP 异步通讯类 包括服务器 和 客户端 测试demo,客户端可同时链接多个服务器,提供AEBellTCPServerSDK.dll 和 AEBellTCPClientSDK.dll 使用者可简单调用接口完成tcp数据通讯功能。
labview modbus tcp通讯llb文件,可方便快捷的建立modbus tcp 子vi