This code snippet demonstrates a simple echo server. The Client sends the string "Hello World" to the server and the server echo's back the string to the client.
Client
import java.net.*;
import java.io.*;
class Client{
public static void main(String args[]){
try {
Socket skClient = new Socket( "127.0.0.1", 1234);
System.out.println( "Connected to server!!!");
OutputStreamWriter sWriter = new OutputStreamWriter(skClient.getOutputStream());
sWriter.write( "Hello World\n");
sWriter.flush();
InputStreamReader sReader = new InputStreamReader(skClient.getInputStream());
BufferedReader bReader = new BufferedReader(sReader);
String serverResponse = bReader.readLine();
System.out.println(serverResponse);
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
}
Server
import java.net.*;
import java.io.*;
class Server{
public static void main(String args[]){
System.out.println( "Server started");
try {
ServerSocket skServer = new ServerSocket(1234);
while (true){
Socket skClient = skServer.accept();
InputStreamReader sReader = new InputStreamReader(skClient.getInputStream());
BufferedReader bReader = new BufferedReader(sReader);
String clientResponse = bReader.readLine();
System.out.println( "Sent from client: " + clientResponse);
OutputStreamWriter sWriter = new OutputStreamWriter(skClient.getOutputStream());
sWriter.write(clientResponse + "\n");
sWriter.flush();
}
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
}
No comments:
Post a Comment