A simple example of socket-based communication between Java programs and C Programs in Linux

Source: Internet
Author: User
Tags htons

In this example, the C language serves as the server, and the Java end serves as the client.

The 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>

Int sockfd, newfd;
Void * read_socket ();

Int main ()
{
Int ret;
Pthread_t read_tid, write_tid;
Struct sockaddr_in server_addr;
Server_addr.sin_family = af_inet;/* set the domain to IPv4 */
Server_addr.sin_addr.s_addr = inaddr_any;/* bind to the inaddr_any address */
Server_addr.sin_port = htons (5678);/* The communication port number is 5678. Note that you must use the htons function to handle this problem. You cannot write 5678 directly. Otherwise, it may not be connected */
Sockfd = socket (af_inet, sock_stream, 0 );
If (sockfd <0)
{
Printf ("An error occurred while calling the socket function to create the socket descriptor! \ N ");
Exit (1 );
}
Printf ("the socket function is successfully called to create the socket descriptor! \ N ");
Ret = BIND (sockfd, (struct sockaddr *) (& server_addr), sizeof (server_addr ));
Perror ("server ");
If (Ret <0)
{
Printf ("An error occurred while calling the BIND function to bind the socket and address! \ N ");
Exit (2 );
}
Printf ("Call the BIND function to bind the socket and address! \ N ");
Ret = listen (sockfd, 4 );
If (Ret <0)
{
Printf ("An error occurred while calling the listen function. The server cannot be declared as accepted! \ N ");
Exit (3 );
}
Printf ("the listen function is called successfully, and the server can accept the connection request! \ N ");
Newfd = accept (sockfd, null, null);/* newfd connects to the client that calls connect */
If (newfd <0)
{
Printf ("An error occurred while calling the accept function. connection requests cannot be accepted. Connection establishment failed! \ N ");
Exit (4 );
}
Printf ("the accept function is called successfully, and the connection between the server and the client is established successfully! \ N ");

/** Create a thread on the server to read data from the socket. Of course, a new thread is not required here. You can write data directly in the original thread **/
Pthread_create (& read_tid, null, read_socket, null );


/******************** Sleep the original thread ************** **********/
While (1)
{
Sleep (10000 );
}
}

/***************** Read data from the socket ***************** ***/
Void * read_socket ()
{
Int recv_num, recv_num_total = 0;
Char recv_buf [50];
While (1)
{
Memset (recv_buf, 0, sizeof (recv_buf);/* clear the recv_buf cache */
Recv_num = Recv (newfd, recv_buf, 26, 0 );
If (recv_num <0)
Printf ("server: failed to call Recv to receive! \ N ");
Else if (recv_num> 0)
{
Recv_num_total + = recv_num;
Printf ("server side: Successful receipt by calling Recv! % D bytes received this time. The content is \ "% s \". Received % d bytes of data. \ N ", recv_num, recv_buf, recv_num_total );
Sync ();
}
Else/* If the received data is 0, the connection between the server and the client has been interrupted */
{
Printf ("server: the connection to the client has been interrupted. Currently, % d bytes of data are 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 class client {
Static socket server;

Public static void main (string [] ARGs) throws exception {
Servers = new socket (inetaddress. getlocalhost (), 5678 );
Bufferedreader in = new bufferedreader (New inputstreamreader (server. getinputstream ()));
Printwriter out = new printwriter (server. getoutputstream ());
Bufferedreader Wt = new bufferedreader (New inputstreamreader (system. In ));

While (true ){
String STR = wt. Readline ();
Out. println (STR );
Out. Flush ();
If (Str. Equals ("end ")){
Break;
}
}
Server. Close ();
}
}

Save the server program as server. C, and the client program as client. java.

Compile:
Gcc-O Server-lpthread server. c
Javac client. Java

Run the server and client respectively on two terminals:
./Server
Java client

/// // The client running result //////////// ////////////////////
Hello, this is a socket test! (Input some text by yourself)
Good
/// // Server running result //////////// ////////////////////
The socket descriptor is successfully created by calling the socket function!
Server: Success
The BIND function is successfully called to bind the socket and address!
The listen function is successfully called and the server can accept the connection request!
The accept function is successfully called and the connection between the server and the client is established!
Server: Recv is successfully called! This time, 26 bytes are received, with the content "Hello, this is a socket tes ". A total of 26 bytes of data are received.
Server: Recv is successfully called! 3 bytes received this time. The content is: "t!
". A total of 29 bytes of data are received.
Server: Recv is successfully called! Five bytes are received this time. The content is: "Good
". A total of 34 bytes of data are received.

======================================

The communication is successful. The first message sent by the client exceeds the number of bytes (26 bytes, recv_num = Recv (newfd, recv_buf,26, 0); Set), the server receives the message twice.

In addition, the line break entered by the client is also received, so you can see the returned result in the blue font, T! There is a line break next to it, and three characters are received at the same time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.