A simple example of a Linux Java program communicating with a C language program through a socket
this morning, I experimented with a Java program communicating with a C language program through a socket. Because did not learn Java, so just write the C language side of the code, the Java side of the code is from the Web other articles found, after a small number of changes to the C language End program communication success. In this example, the C language side acts as a server, and the Java side as the client code is as follows:/****************** Server program *****************/#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<string.h>#include<stdlib.h>#include<sys/un.h>#include<pthread.h>#include<arpa/inet.h>intSOCKFD,NEWFD;void*Read_socket ();intMain () {intret; pthread_t Read_tid,write_tid; structsockaddr_in server_addr; Server_addr.sin_family=af_inet;/*set the domain to IPV4*/server_addr.sin_addr.s_addr=inaddr_any;/*bind to Inaddr_any address*/Server_addr.sin_port=htons (5678);/*Communication port number is 5678, note that here must be treated with htons function, not directly write 5678, otherwise may not be able to connect*/SOCKFD=socket (Af_inet,sock_stream,0); if(sockfd<0) {printf ("calling the socket function to create a socket descriptor error! \ n"); Exit (1); } printf ("call the socket function to establish the socket descriptor successfully! \ n"); RET=bind (SOCKFD, (structSOCKADDR *) (&SERVER_ADDR),sizeof(SERVER_ADDR)); Perror ("Server"); if(ret<0) {printf ("calling bind function bound socket and address error! \ n"); Exit (2); } printf ("call the BIND function to bind the socket to the address successfully! \ n"); RET=listen (SOCKFD,4); if(ret<0) {printf ("Error calling the Listen function, unable to declare that the server is ready to accept the connection! \ n"); Exit (3); } printf ("the call to the Listen function succeeds, declaring that the server is ready to accept the connection request! \ n"); NEWFD=accept (Sockfd,null,null);/*NEWFD connecting to a client that calls connect*/ if(newfd<0) {printf ("Error calling accept function, unable to accept connection request, failed to establish connection! \ n"); Exit (4); } printf ("call the Accept function successfully, the server and the client establish a successful connection! \ n"); /** Server-side set up a thread, responsible for reading data from the socket, of course, here is not necessarily to create a new thread, directly in the original thread can write **/Pthread_create (&read_tid,null,read_socket,null); /********************* make the original thread sleep ************************/ while(1) {Sleep (10000); }}/****************** reading data from socket ********************/void*Read_socket () {intRecv_num,recv_num_total=0; Charrecv_buf[ -]; while(1) {memset (Recv_buf,0,sizeof(RECV_BUF));/*clear the Recv_buf buffer .*/Recv_num=RECV (Newfd,recv_buf, -,0); if(recv_num<0) printf ("Server-side: Call recv receive failed! \ n"); Else if(recv_num>0) {Recv_num_total+=Recv_num; printf ("Server-side: Call RECV receive success! This time,%d bytes were received with the content: \ "%s\". A total of%d bytes of data were received. \ n", Recv_num,recv_buf,recv_num_total); Sync (); } Else/*The data received is 0, indicating that the connection between the server and the client has been interrupted*/{printf ("server-side: The connection to the client has been interrupted, and a total of%d bytes of data is currently received. The server will wait for the client connection again. \ n", Recv_num_total); NEWFD=accept (Sockfd,null,null);/*when the client exits, it starts receiving the client connection again*/} sleep (1); }}/****************** Client Program *****************/import java.net.*; import java.io.*; Public classClient {StaticSocket server; Public Static voidMain (string[] args) throws Exception {server=NewSocket (Inetaddress.getlocalhost (),5678); BufferedReaderinch=NewBufferedReader (NewInputStreamReader (Server.getinputstream ())); PrintWriter out=NewPrintWriter (Server.getoutputstream ()); BufferedReader WT=NewBufferedReader (NewInputStreamReader (System.inch)); while(true) {String str=Wt.readline (); out. println (str); out. Flush (); if(Str.equals ("End")) { Break; }} server.close ();}} Save server-side program as SERVER.C, client program as Client.java compile: gcc-O Server-Lpthread Server.cjavac Client.java Run the server and client separately under two terminals:./Serverjava Client/////////////////////////Client Run results////////////////////////////////Hello This isA socket test!(enter some text yourself) Good/////////////////////////Server Run results////////////////////////////////call the socket function to establish the socket descriptor successfully! Server:success call bind function bind socket with address succeeded! The call to the Listen function succeeds, declaring that the server is ready to accept the connection request! Call the Accept function successfully, the server and the client establish a successful connection! Server-side: Call RECV receive success! This time, 26 bytes are received, the content is:"Hello,this is a socket TES". A total of 26 bytes of data were received. Server-side: Call RECV receive success! This time, 3 bytes are received, the content is:"t!". A total of 29 bytes of data were received. Server-side: Call RECV receive success! This time, 5 bytes are received, the content is:"Good". A total of 34 bytes of data were received. ================================= Visible communication is successful, where the first message sent by the client exceeds the number of bytes per read specified in the service-side program (26 bytes, in this sentence recv_num=RECV (Newfd,recv_buf, -,0), the service ends up receiving the message two times. In addition, the newline character entered by the client is also received, so you can see the blue font in the return result, T!there is a newline at the back, which shows that 3 characters are received at the same time. Reprinted from: http://blog.chinaunix.net/uid-24330370-id-2620040.html
A simple example of a Linux Java program communicating with a C language program through a socket