JavaSoket线程服务器向特定客户端发送消息

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (583)

正在开发一个Client-Server Java GUI(Swing)应用程序,我已经成功地创建了一个线程服务器类来接收来自客户端的消息,还有一个客户端类向服务器发送消息,客户机和服务器都是GUI应用程序,我正在为我的Internet Caffe开发一个局域网订购系统。我刚开始进行套接字编程,我现在需要的是一种方法,当服务器GUI应用程序的用户通过单击JLabel来查看GUI中的顺序时,通过单击JLabel将消息发送到客户端。JLabel会在消息到达时更改图标。

那么,如何从服务器向发送触发该特定JLabel的消息的特定客户端发送消息呢?以及如何向包含该消息的客户端用户显示JOption窗格(客户端有几个JPanel类)

发送消息的Client类:

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();
}
}

线程服务器

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);
        }
    }
}
}
提问于
用户回答回答于

套接字建立端到端连接,因此每个套接字都连接到另一个套接字上,返回的对象是Socket。不仅是一个套接字,而且是直接连接到发出请求的客户端的套接字。

已经在从套接字中读取以检查连接是否已关闭或“退出命令”是否已发出。现在可以简单地在你的else-条款DataOutputStream较早时创建:

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) {
      ...
    } ...
}

但是请注意,你的repsonse字符串需要以'\n'性格,取决于你客户的“阅读逻辑”。

扫码关注云+社区

领取腾讯云代金券