Server
To make a Socket connection, you need to know the IP and the port. Start the server and wait for clients requests.
package messages;
import java.io.*;
import java.net.*;
public class TestServer{
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(4242);
System.out.println("Server started ...");
while(true) {
Socket socket = serverSocket.accept();
PrintWriter writer =
new PrintWriter(socket.getOutputStream());
writer.println("Hello Client!"); // write message to client
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client
Make a connection and read from server.
package messages;
import java.io.*;
import java.net.*;
public class TestingApp{
public static void main(String[] args) {
System.out.println("Client started");
try {
// make a connection to the server
Socket socket = new Socket("127.0.0.1", 4242);
// ask the socket for an input stream
InputStreamReader streamReader =
new InputStreamReader(socket.getInputStream());
// read
BufferedReader reader =
new BufferedReader(streamReader);
String message = reader.readLine();
System.out.println("The server message is: " + message);
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
Last update: 357 days ago