Read and write message from ServerSocket - Java Network

Java examples for Network:ServerSocket

Description

Read and write message from ServerSocket

Demo Code

import java.io.*;
import java.lang.ClassNotFoundException;
import java.net.*;
 
public class SocketServer{
    /*from ww w.j av a 2 s .  c  om*/
    private static ServerSocket server;
    private static int port = 3002;

    public static void main(String args[]) throws IOException, ClassNotFoundException{
        server = new ServerSocket(port);
        while(true){
            System.out.println("Waiting for client request");
            Socket socket = server.accept();
            BufferedReader ois = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String message = ois.readLine();
            System.out.println("Message Received: " + message);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject("Hi Client "+message);
            ois.close();
            oos.close();
            if(message.equalsIgnoreCase("exit")) break;
        }
        System.out.println("Shutting down Socket server!!");
        server.close();
    }     
}

Related Tutorials