简体   繁体   中英

Java Soket Threaded Server sending messages back to specific client

i am developing a Client-Server Java GUI(Swing) application , i have succsesfully created Threaded Server class that receives messages from clients , and a Client class that sends message to the server , both Client and Server are GUI applications , i am developing a lan ordering system for my internet caffe.. I am new to socket programing , what i need now is a way to send a message from Server to Client when user of Server GUI application views the order in a GUI by clicking a JLabel that changes icon when message arrives..

So how to send a message from the Server to that specific Client that send the message that triggered that specific JLabel ? And how to show JOptionpane to to Client user containing that message (client has several JPanel classes)

Client class that sends the message:

package questorderingsystem.engine;

import java.io.BufferedWriter; 
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
    public class SendItemAndIp {

    private static Socket socket;
    public static String message = "";
    public static void sendToServer(String item) throws UnknownHostException, IOException{
    InetAddress IP= InetAddress.getLocalHost();
    String ipadr = IP.toString();
    String PCNUM = ipadr.substring(ipadr.length() - 2);

    //IP SERVERAA 
    String host = "192.168.55.151";
    int port = 1978;
        InetAddress address = InetAddress.getByName(host);
        socket = new Socket(address, port);
        //Send the message to the server
        OutputStream os = socket.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os);
        BufferedWriter bw = new BufferedWriter(osw);
        String oneLine = item.replace("\n", "%");
        String sendMessage = oneLine +"/"+ PCNUM;
        bw.write(sendMessage);
        bw.flush();
        socket.close();
}
}

Threaded Server

package questorderingsystemserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ThreadedEchoServer {

static final int PORT = 1978;

public static void startServer() {
    ServerSocket serverSocket = null;
    Socket socket = null;

    try {
        serverSocket = new ServerSocket(PORT);
    } catch (IOException e) {
        e.printStackTrace();

    }
    while (true) {
        try {
            socket = serverSocket.accept();
        } catch (IOException e) {
            System.out.println("I/O error: " + e);
        }
        // new thread for a client
        new EchoThread(socket).start();
    }
}
}

EchoServer

package questorderingsystemserver;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JLabel;

public class EchoThread extends Thread {
protected Socket socket;



}
public EchoThread(Socket clientSocket) {
    this.socket = clientSocket;
}
public void run() {
    InputStream inp = null;
    BufferedReader brinp = null;
    DataOutputStream out = null;
    try {
        inp = socket.getInputStream();
        brinp = new BufferedReader(new InputStreamReader(inp));
        out = new DataOutputStream(socket.getOutputStream());
    } catch (IOException e) {
        return;
    }
    String line;
    while (true) {
        try {
            line = brinp.readLine();
            if ((line == null) || line.equalsIgnoreCase("QUIT")) {
                socket.close();
                return;
            } else {
                //do something

                out.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } catch (UnsupportedAudioFileException ex) {
            Logger.getLogger(EchoThread.class.getName()).log(Level.SEVERE, null, ex);
        } catch (LineUnavailableException ex) {
            Logger.getLogger(EchoThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
}

Sockets establish end-to-end-connections and therefore each socket it connected to another specific one. A ServerSocket is slightly different. Take a look at the return of ServerSocket::accept . The returned object is a Socket . Not only one socket but the one directly connected to the client who issued a request. Since you create a new EchoThread for each ServerSocket#accept call each EchoThread has it's of connection to it's own Client.

You're already reading from the socket to check if the connection has been closed or 'QUIT command' has been issued. Now you can simply respond in your else -clause with the DataOutputStream created earlier:

while (true) {
    try {
        line = brinp.readLine();
        if ((line == null) || line.equalsIgnoreCase("QUIT")) {
            socket.close();
            return;
        } else {
            //writing here:
            out.write("Some response text\n".getBytes());
            out.flush();
        }
    } catch (IOException e) {
      ...
    } ...
}

But note that your repsonse String needs to end with a '\\n' character, depending on your 'reading logic' of your client.

You are almost done, as you specified the first command as "QUIT", so you may implement more commands as you wish.

The good part is handling the input and output using the BufferedReader and DataOutputStream .

Please note if you like to work with strings for communication between client and server, so you may go for PrintStream or PrintWriter instead of DataOutputStream .

in thread server file/class, place this line new EchoThread(socket).start(); after you accept the socket in side the try(it's now safe).

In client class/file, as you send some command for server, then you may expecting some result too. So just like echo class you created, you may do the same thing for client and process the responses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM