I am using Dynamic C V9.62 to develop on a BL2600 SBC.
Essentially, I want to open a socket to a remote instrument (IP:PORT), send a short message to that instrument, and then read the instrument’s reply through the same socket. I am new to socket programming and none of the examples I tried gave me enough insight on how to do this.
A good example for TCP is the Modbus TCP Master and slave libraries which use small packets over TCP/IP. These can be found in the Lib\Rabbit4000\Modbus folder.
On the UDP side of things, the Dynamic C BACnet stack at http://bacrabbit.sourceforge.net/ uses UDP to send small to medium packets over UDP.
These examples don’t use the same socket to send and receive data. Would be good to have an example of a client that sends a string to the server, and the server replies on the same socket (the client waits for the reply).
Define the number of socket buffers that will be allocated for
UDP sockets. We only need one UDP socket, so one socket buffer
will be enough.
*/ define MAX_UDP_SOCKET_BUFFERS 3
/*
UDP demo configuration
*/
/* what local UDP port to use - we receive packets only sent to this port */ define LOCAL_PORT 10001
/*
If REMOTE_IP is set to -1, we will accept packets from anybody.
If it is set to 0, we will accept packets from anybody, but
the first host to connect to us will complete the socket with
their IP address and port number. At that point, the local socket
will be limited to that host only.
If it is set to an IP address, the socket will only accept packets
from that IP.
*/ define REMOTE_IP -1 // accept packets from all hosts
//define REMOTE_IP 0 // accept packets from first host
//define REMOTE_IP IPADDR(192,168,2,71) // accept from this addr only
/********************************
End of configuration section *
********************************/
/* receive one packet (heartbeat) */
int receive_packet(void)
{
static char buf[128];
int len;
longword remoteIP;
word remotePort;
udp_Socket remoteSock;
#GLOBAL_INIT
{
memset(buf, 0, sizeof(buf));
}
// receive the packet
//len = udp_recv(&sock, buf, sizeof(buf));
len = udp_recvfrom(&sock, buf, sizeof(buf), &remoteIP, &remotePort);
if (-1 == len) return 0; // no packet read. return
printf("Received %i bytes -> %s
", len, buf);
tcp_tick(NULL); // *** VERY IMPORTANT ***
len = udp_sendto(&sock, buf, len, remoteIP, remotePort);
printf("Sent back %i bytes to remote %lX, port %u
", len, remoteIP, (int)remotePort);
return 1;
}
void main()
{
// Start network and wait for interface to come up (or error exit).
sock_init_or_exit(1);