The Java server and the Linux C client communicate with each other using UDP protocol, and the most critical point is the unification of data structure. For example, in C a char type is 8bit, in Java, Char is 16bit, so C and Java char types cannot be converted directly to each other. In this routine, the char type of C and the byte type of Java, two data types are 8bit, which guarantees the correct transmission of data in one of the basic conditions.
The Java server code is as follows:
Import java.io.*;import java.lang.*;import java.net.*;p ublic class udpserver{private Datagramsocket server_sock; Private Datagrampacket PAC; private byte recv_buffer[]; Private String recv_string; Public Udpserver () {Init (); } public void Init () {try {//Listen port set to 1234 server_sock=new Datagramsocket (1234 ); Recv_buffer=new byte[1024];//receive buffer, byte type pac=new datagrampacket (recv_buffer,recv_buffer.length);//Construct a packet Recv_string= ""; while (true)//loop accepts data {server_sock.receive (PAC);//block receive data//convert byte[] to string Recv_string=new string (Recv_buffer,0,pac.getlength ()); System.out.println (recv_string); }} catch (Exception e) {e.printstacktrace (); }} public static void Main (String args[]) {new Udpserver (); }}
The Linux C client code is as follows:
#include <sys/types.h> #include <sys/socket.h> #include <string.h> #include <netinet/in.h># Include <stdio.h> #include <stdlib.h> #include <arpa/inet.h> #include <unistd.h>int main (int ARGC, char **argv) {int fd; Declares a V4 address structure, which is used to store information such as the address of a communication struct sockaddr_in address; int Address_len; Ready-to-send string, char char line[100] = "Sending string:client to server!"; int n; Set-up interface FD = socket (af_inet, SOCK_DGRAM, 0),//af_inet and sock_dgram combination corresponding to UDP protocol//connection The V4 address structure is cleared 0 bzero (&address, sizeof (address)); Set the relevant properties address.sin_family = Af_inet; ADDRESS.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1"); Address.sin_port = htons (1234); Address_len = sizeof (address); Send Data sendto (FD, line, strlen (line) +1, 0, (struct sockaddr *) &address, SIzeof (address)); printf ("Send string success\n");}
The program is simple for reference only, Java to do the client and C server This form is similar to the above code, do not repeat this. It is important to note that the end of the string type in Java has no ' char[', which is different from the end of the C language, but it does not need to be considered for UDP communication.
UDP communication between the Java server and the Linux C client