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 Java host and client to communicate using Socket |
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:
- Client and Server example II, ServerSocket stay in loop
- Client and Server example III, run socket operation in background thread
- Communication between Android + Raspberry Pi
- Client and Server example IV, with option to request Read Temperature
- Client and Server example V, pass ArrayList of object in socket
- client send something to server
- bi-direction communication, between echo server and client
0 تعليقات