Engineering Full Stack Apps with Java and JavaScript
We will see how to communicate between a server and a client using simple network programming using sockets. You can get started with socket programming. Also, a simple client server program might be needed in many situations; you can just copy paste the basic code below and add to it.
We will create a simple server that accepts a client and sends a string message to the client. Client simply prints the message from server in the console.
Server.java
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;public class Server {
public static void main(String[] args) throws IOException {System.out.println("Server");
ServerSocket ss = new ServerSocket(7777);
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
PrintStream ps = new PrintStream(os);
ps.println("Hello from server");ss.close();
s.close();
ps.close();
}
}
Client.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;public class Client {
public static void main(String[] args) throws UnknownHostException,
IOException {
Socket s = new Socket("mchej01", 7777);
InputStream is = s.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
System.out.println("message:" + br.readLine());
br.close();
s.close();
}
}
This is a very simple program, but still let me know if you find any issues or have any doubts,