我正在尝试将tcp数据包发送到服务器,但无法使用mbed OS,stm32核板和Adafruit fona 3g进行发送。我正在使用以下链接中找到的.cpp文件和.h文件:
https://os.mbed.com/users/Nels885/code/Adafruit_FONA_3G/file/b18cfba4283a/
我已经分别测试了客户端和服务器。通过客户端,我能够与回显服务器建立连接。对于服务器,我使用计算机通过套接字将数据发送到EC2实例,并且这两种方法都可以成功通信。但是,我无法使两者一起工作,并且我认为问题出在收发器上,因为我无法确认收发器是否正在发送数据。
客户代码:
#include "mbed.h"
#include "Adafruit_FONA.h"
#define FONA_RST D4
#define FONA_TX D1
#define FONA_RX D0
#define FONA_RI D7 //not used
char replybuffer[255];
Adafruit_FONA_3G fona(FONA_TX, FONA_RX, FONA_RST, FONA_RI);
Serial pc(USBTX, USBRX);
int main()
{
while(1){
fona.TCPinitialize();
pc.printf ("initialize \n");
char Timeout[21];
fona.getTCPtimeout(Timeout);
pc.printf ("timeout \n");
char Server[] = "18.216.194.185";
uint16_t Port = 10001;
fona.TCPconnect(Server,Port);
pc.printf ("connect \n");
char Packet[] = "Pick Up %";
fona.TCPsend(Packet);
pc.printf ("send \n");
fona.sslTCPsend(Packet);
pc.printf ("ssl send \n");
fona.TCPclose();
pc.printf ("close \n");
}
}
服务器代码:
// Server side C/C++ program to demonstrate Socket programming
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <iostream>
#include <string.h>
#define PORT 10001
int main(int argc, char const *argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = (char*)"Henlo from server";
std::string message;
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 8083
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
//check connection
int error_code;
socklen_t error_code_size = sizeof(error_code);
int connectionState = getsockopt(server_fd, SOL_SOCKET, SO_ERROR,
&error_code, &error_code_size);
if (error_code != 0)
{
fprintf(stderr, "socket error: %s\n", strerror(error_code));
}
else std::cout << "connection established with port 10001\n";
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
valread = read( new_socket , buffer, 1024);
printf("%s\n",buffer );
message = buffer;
std::cout << "the message I recieved says " << message << '\n';
send(new_socket , hello , strlen(hello) , 0 );
printf("Hello message sent\n");
return 0;
}