Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int port;
- ServerSocket server=null;
- Socket socket=null;
- ExecutorService exec = null;
- ArrayList clients = new ArrayList<DataOutputStream>();
- DataOutputStream dos=null;
- public static void main(String[] args) throws IOException {
- Server serverobj=new Server(2000);
- serverobj.startServer();
- }
- Server(int port){
- this.port=port;
- exec = Executors.newFixedThreadPool(2);
- }
- public void startServer() throws IOException {
- server=new ServerSocket(2000);
- System.out.println("Server running");
- while(true){
- socket=server.accept();
- dos = new DataOutputStream(socket.getOutputStream());
- clients.add(dos);
- ServerThread runnable= new ServerThread(socket,clients,this);
- exec.execute(runnable);
- }
- }
- private static class ServerThread implements Runnable {
- Server server=null;
- Socket socket=null;
- BufferedReader brin;
- Iterator<DataOutputStream> it=null;
- Scanner sc=new Scanner(System.in);
- String str;
- ServerThread(Socket socket, ArrayList clients ,Server server ) throws IOException {
- this.socket=socket;
- this.server=server;
- System.out.println("Connection successful with "+socket);
- brin=new BufferedReader(new InputStreamReader(socket.getInputStream()));
- it = clients.iterator();
- }
- @Override
- public void run() {
- try{
- while ((str = brin.readLine()) != null) {
- while (it.hasNext()) {
- try{
- DataOutputStream oss=it.next();
- oss.writeChars(str);
- }
- catch(Exception ex){
- System.out.println("Error 1 "+ex);
- }
- }
- }
- brin.close();
- socket.close();
- }
- catch(IOException ex){
- System.out.println("Error 2 "+ex);
- }
- }
- }
- String str;
- Socket socket=new Socket("127.0.0.1",2000);
- BufferedReader brin=new BufferedReader(new InputStreamReader(socket.getInputStream()));
- PrintStream prout=new PrintStream(socket.getOutputStream());
- BufferedReader bread=new BufferedReader(new InputStreamReader(System.in));
- System.out.println("Send to Server:");
- str=bread.readLine();
- prout.println(str);
- while(true){
- str=brin.readLine();
- System.out.print("Server:"+str+"n");
- }
- }
Add Comment
Please, Sign In to add comment