Ticker

6/recent/ticker-posts

Java exercise - Implement client and server to communicate using Socket, step-by-step

This examples create two separated program (host and client) with Java, using java.net.Socket.

In host side, it start ServerSocket and wait for client. In client side, the IP address of host is hard coded, user have to enter port number of host manually. Once connected, the host will send a message to client and exit the program.

Implement host and client to communicate using Socket
Implement Java host and client to communicate using Socket
In the demo video on bottom of this post, the host run on Raspberry Pi, the client run on the same Raspberry Pi, and run on another PC running Windows 8.1.

host.java
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.IOException;

class host
{
public static void main(String srgs[])
{
try{
ServerSocket serverSocket = new ServerSocket(0);
System.out.println("I'm waiting here: " + serverSocket.getLocalPort());

Socket socket = serverSocket.accept();
System.out.println("from " +
socket.getInetAddress() + ":" + socket.getPort());

OutputStream outputStream = socket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print("Hello Raspberry Pi");
printStream.close();

socket.close();
}catch(IOException e){
System.out.println(e.toString());
}

}
}


client.java
import java.net.Socket;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.UnknownHostException;

class client{

public static void main(String args[])
{
if(args.length == 0){
System.out.println("usage: java client ");
System.exit(1);
}

int port = isParseInt(args[0]);
if(port == -1){
System.out.println("usage: java client ");
System.out.println(": integer");
System.exit(1);
}

try{
//IP is hard coded
//port is user entry
Socket socket = new Socket("192.168.111.108", port);
InputStream inputStream = socket.getInputStream();

ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];

int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
}

socket.close();

System.out.println(byteArrayOutputStream.toString("UTF-8"));

}catch(UnknownHostException e){
System.out.println(e.toString());
}catch(IOException e){
System.out.println(e.toString());
}

}


private static int isParseInt(String str){

int num = -1;
try{
num = Integer.parseInt(str);
} catch (NumberFormatException e) {
}

return num;
}

}




Download Java code of host.java and client.java.

Step-by-step:

إرسال تعليق

0 تعليقات