warwcat
warwcat

Reputation: 339

Receiving two messages at the same time by sockets

I'm training with sockets, and for that I'm doing a chat service in my localhost. My problem is when send query to server, to use an nickname the server must send me a confirmation or an error (nickname can be in use or not). But only when the client send an second squery to server is when server gives an answer to the clien:t the confirmation and the answear to second query at same time. This is not what I want, I already try to find if server receives a a query or not and it recieves.

My server code to give an username:

static private void resolveUsername(Selector sel, SelectionKey key, String nick) throws IOException {
for (SelectionKey k : sel.keys()) {
    if(k.isValid() && k.channel() instanceof SocketChannel)

    if(((User)k.attachment()).getNick().equals(nick)) {
        SocketChannel sct = (SocketChannel)key.channel();
        sct.write(enc.encode(CharBuffer.wrap("ERROR")));
        return;
    }
}

if( ((User)key.attachment()).state() == State.INSIDE) {
    for (SelectionKey k : sel.keys()){
    if(k.isValid() && k.channel() instanceof SocketChannel){
        if(!((User)k.attachment()).getNick().equals(((User)key.attachment()).getNick())){
        SocketChannel sct = (SocketChannel)key.channel();
        sct.write(enc.encode(CharBuffer.wrap("NEWNICK "+((User)key.attachment()).getNick() +" "+ nick)));   }
    }
    }
}
((User)key.attachment()).setNick(nick);
SocketChannel sct = (SocketChannel)key.channel();
sct.write(enc.encode(CharBuffer.wrap("OK")));
}

My server code sends message:

message = it.getNick() +":"+ message;

for (SelectionKey k : sel.keys()) {
       if(k.isValid() && k.channel() instanceof SocketChannel) {
           SocketChannel sct = (SocketChannel)k.channel();
           sct.write(enc.encode(CharBuffer.wrap(message)));

       }
    }

My client reading code in a separate thread:

 public void run() {
   while(open) {
       String modifiedSentence ="";

       try {
           modifiedSentence = inFromServer.readLine();
       } catch(IOException e) {
           System.out.println("ERROR");}
           System.out.println(modifiedSentence);

           if(!modifiedSentence.equals(""))
               chatArea.append(modifiedSentence+'\n');
       }
    }

My send query to server:

public void newMessage(String message) throws IOException {
    outToServer.writeBytes(message+'\n');
}

UPDATE: I used netcat to test receiving messages from the server , and it receives correctly , so I think the client side is what is wrong. But I think I 'm doing all correctly I will put my client code if you need.

public class ChatClient  {
    JFrame frame = new JFrame("Chat Client");
    private JTextField chatBox = new JTextField();
    private JTextArea chatArea = new JTextArea();
    private Thread t;
    private Socket clientSocket;
    private DataOutputStream outToServer;

    private BufferedReader inFromServer;

    public void printMessage(final String message) {
         chatArea.append(message);
    }


    public ChatClient(String server, int port) throws IOException {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add(chatBox);
        frame.setLayout(new BorderLayout());
        frame.add(panel, BorderLayout.SOUTH);
        frame.add(new JScrollPane(chatArea), BorderLayout.CENTER);
        frame.setSize(500, 300);
        frame.setVisible(true);
        chatArea.setEditable(false);
        chatBox.setEditable(true);
        chatBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
        try {
            newMessage(chatBox.getText());
        } catch (IOException ex) {
        } finally {
            chatBox.setText("");
        }
        }
    });



      clientSocket = new Socket(server, port);
      outToServer = new DataOutputStream(clientSocket.getOutputStream());
      inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      t =new Thread(new Reader(chatArea, clientSocket,inFromServer));
      t.start();

     }

public void newMessage(String message) throws IOException {

     outToServer.writeBytes(message+'\n');

}

public void run() throws IOException {

    while(!clientSocket.isClosed()){
    }
    Reader.open=false;


}

public static void main(String[] args) throws IOException {
    ChatClient client = new ChatClient(args[0], Integer.parseInt(args[1]));
    client.run();
    }

}



class Reader implements Runnable {
    private JTextArea chatArea;
    private Socket clientSocket;
    public static  Boolean open = true;
    private BufferedReader inFromServer;

    public Reader(JTextArea chatArea,Socket clientSocket,BufferedReader inFromServer){
        this.chatArea = chatArea;
        this.clientSocket = clientSocket;
        this.inFromServer = inFromServer;
    }
    public void run(){
        while(open){
            System.out.println("TTT\n");
            String modifiedSentence ="";

            try{

                 modifiedSentence = inFromServer.readLine();
            }catch(IOException e){
                 System.out.println("ERROR");
            }


            chatArea.append(modifiedSentence+'\n');
        }


    }
}

Thanks for your time.

Upvotes: 1

Views: 150

Answers (1)

Armali
Armali

Reputation: 19375

I used netcat to test receiving messages from the server , and it receives correctly , so I think the client side is what is wrong. But I think I 'm doing all correctly …

What you most probably aren't doing correctly is that in the client you use .readLine(), which reads a line of text, while in the server you don't terminate all messages with a line feed ('\n') or a carriage return ('\r').

Upvotes: 1

Related Questions