0

Im new to threads, and would like to get experience so I am trying to
build a chat server. The idea is to have one thread read from the client socket,
while another thread writes to the client socket. (like AIM) I cannot get them to execeute
concurrently; Need help, any tips, codeeee ?

import java.io.*;
import java.util.*;
import java.net.*;


public class ChatServer implements Runnable{

    private static ServerSocket server;
    private static Socket client;
    private boolean isReader;

    public ChatServer(boolean reader) throws Exception{

        isReader = reader;

        if(server == null)
            server = new ServerSocket(1234);


    }


    public static void main(String[] args){

        try{

            Runnable r = new ChatServer(true);
            Runnable w = new ChatServer(false);

            Thread t = new Thread(r);
            Thread o = new Thread(w);


            t.start();
            o.start();



        }catch(Exception er){
            System.out.println(er);
        }


    }//main



    public void run() {


        try{


            System.out.println(this);


            if(client == null){
                client = server.accept();
                System.out.println("Connected");
            }

            if(this.isReader == true){
                System.out.println("read ex");
                this.read();
            }else{
                System.out.println("write ex");
                this.write();
            }

        }catch(Exception error){

            System.out.println(error);

        }



    }//run

    public void read() throws Exception{

        System.out.println("Reading\n");

        DataInputStream read = new DataInputStream(client.getInputStream());
        int n ;
        while((n = read.read()) != -1)
            System.out.print((char)n);



    }
    public void write() throws Exception{

        System.out.println("Writing\n");

        DataOutputStream write = new DataOutputStream(client.getOutputStream());

        write.writeBytes("Chat Server\n");
        write.flush();

        Scanner sc = new Scanner(System.in);

        while(true){

            String line = sc.nextLine();
            write.writeBytes(line + "\n");

            write.flush();
        }


    }

}//class
2
Contributors
1
Reply
17
Views
4 Years
Discussion Span
Last Post by james6754
0

Create a class for Reading and one for writing, create a thread for each...this will allow you to read from and write to the socket. I posted a code snippet for this a couple of weeks back, check it out it should give you some ideas.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.