Java套接字: how the server can reads multiple lines from the client

标签 java sockets asynchronous

我使用Java编程语言创建一对一的聊天应用程序 我遇到问题:客户端在收到来自服务器的消息之前无法发送新消息。

最佳答案

您应该有一个多线程应用程序。 客户端将运行2个线程: 1) 将在发送按钮上运行的发送者线程。您每次都可以通过单击“发送”按钮创建该线程的新实例。 2) 接收线程将继续持续运行并检查流中是否有任何消息。一旦它在流上收到消息,它就会在控制台上写入相同的消息。

很快就会向您更新代码。 谢谢

很久以前就写过这段代码,类似地,您可以使用其他端口编写服务器

package com.clients;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ClientFullDuplex extends JFrame implements ActionListener {

    private JFrame jframe;
    private JPanel jp1, jp2;
    private JScrollPane jsp;
    private JTextArea jta;
    private JTextField jtf;
    private JButton send;
    private Thread senderthread;
    private Thread recieverthread;
    private Socket ds;
    private boolean sendflag;

    public static void main(String[] args) {
        try {
            ClientFullDuplex sfd = new ClientFullDuplex();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public ClientFullDuplex() throws UnknownHostException, IOException {
        initGUI();
        ds = new Socket("127.0.0.1", 1124);
        initNetworking();
    }

    public void initGUI() {

        jframe = new JFrame();
        jframe.setTitle("Client");
        jframe.setSize(400, 400);
        jp1 = new JPanel();
        jta = new JTextArea();
        jsp = new JScrollPane(jta);

        jtf = new JTextField();
        send = new JButton("Send");
        send.addActionListener(this);

        jp1.setLayout(new GridLayout(1, 2, 10, 10));
        jp1.add(jtf);
        jp1.add(send);

        jframe.add(jp1, BorderLayout.SOUTH);
        jframe.add(jsp, BorderLayout.CENTER);
        jframe.setVisible(true);
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jta.append("hello client");

    }

    @Override
    public synchronized void addWindowListener(WindowListener arg0) {
        // TODO Auto-generated method stub
        super.addWindowListener(arg0);
        new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent arg0) {
                // TODO Auto-generated method stub
                if (ds != null)
                    try {

                        ds.close();
                        System.exit(0);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            }
        };

    }

    public void initNetworking() {
        try {
            recieverthread = new Thread(r1);
            recieverthread.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    Runnable r1 = new Runnable() {

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName()
                        + "Reciver Thread Started");
                recieveMessage(ds);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    };

    Runnable r2 = new Runnable() {

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName()
                        + "Sender Thread Started");
                sendMessage(ds);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    };

    public void recieveMessage(Socket rms) throws IOException {
        while (true) {
            System.out.println(Thread.currentThread().getName()
                    + "Reciver Functionality");
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    rms.getInputStream()));
            String line = br.readLine();
            System.out.println(line);
            jta.append("\nServer:"+line);
        }
    }

    public void sendMessage(Socket sms) throws IOException {

        System.out.println(Thread.currentThread().getName()
                + "Sender Functionality");
        PrintWriter pw = new PrintWriter(sms.getOutputStream(), true);
        String sline = jtf.getText();
        System.out.println(sline);
        pw.println(sline);
        jtf.setText("");

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        if (e.getSource() == send) {
            senderthread = new Thread(r2);
            senderthread.start();
        }
    }

}

关于Java套接字: how the server can reads multiple lines from the client,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28875548/

相关文章:

Java线程等待和通知方法

Android/Iphone 套接字通信

python - Scapy TCP 握手 - Windows

asynchronous - 如何以严格的顺序使用 AFNetworking 2 发送请求?

perl - 如何使用 AnyEvent 和 Perl 并行运行外部命令

javax.jcr.* javadoc 丢失

java - 使用 Lambda 表达式使用 HashMap 替换字符串中的字符

java - 为什么我在 Java 中得到 NoClassDefFoundError?

C++ 套接字不接收传入数据包,在 Python 中工作

javascript - 加载 Javascript : HTTP Requests -v- Asynchronous Loading