简体   繁体   English

Java ServerSocket /套接字聊天程序

[英]Java ServerSocket/Socket Chat Program

i tried to make a little chat program, but it really don't want to work. 我试图制作一个聊天程序,但是它真的不想工作。 My server and client are mostly the same: they create a new socket and a new Chat (GUI). 我的服务器和客户端基本相同:它们创建一个新的套接字和一个新的聊天(GUI)。 Can someone help me find the mistake i made? 有人可以帮助我找到我犯的错误吗?

Server Code: 服务器代码:

import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

import java.net.Socket;
import java.net.ServerSocket;

public class Server {
    private     Chat            ch      = null;
    private     ServerSocket    server  = null;
    private     Socket          s       = null;
    private     BufferedReader  in      = null;
    private     BufferedWriter  out     = null;

    public Server() {
        try {
            server = new ServerSocket(1792);
            s = server.accept();
            in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            ch = new Chat("Server", out);
        } catch (IOException ioe) {

        }

        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        String line = in.readLine();
                        ch.showString(line);
                    } catch (IOException e) {
                        System.exit(0);     // exit program when connection is lost
                        return;
                    }
                }
            }
        }).start();
    }
}

Client Code: 客户代码:

import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

import java.net.Socket;

public class Client {
    private     Chat            ch      = null;
    private     Socket          s       = null;
    private     BufferedReader  in      = null;
    private     BufferedWriter  out     = null;

    public Client() {
        try {
            s = new Socket("localHost", 1792);
            in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            ch = new Chat("Client", out);
        } catch (IOException ioe) {

       }

        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        String line = in.readLine();
                        ch.showString(line);
                    } catch (IOException e) {
                        System.exit(0);     // exit program when connection is lost
                        return;
                    }
                }
            }
        }).start();
    }
}

Chat (GUI) Code: 聊天(GUI)代码:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JLabel;

import java.io.BufferedWriter;
import java.io.IOException;

public class Chat implements ActionListener {
    protected   JFrame          fr;
    private     JPanel          p;
    private     JTextField      tf;
    private     JButton         b;
    private     int             lines   = 20;
    private     JLabel[]        l       = new JLabel[lines];
    private     String          title   = "";
    private     BufferedWriter  out;

    public Chat(String name, BufferedWriter bw) {
        title = name;
        out = bw;

        fr = new JFrame(title);
        fr.setLayout(new BorderLayout());
        fr.setDefaultCloseOperation(fr.EXIT_ON_CLOSE);
        fr.setSize(400, 475);
        fr.setLocationRelativeTo(null);
        fr.setResizable(false);
        fr.setVisible(true);

        Insets in = fr.getInsets();
        int width = fr.getWidth() - in.left - in.right;
        int height = fr.getHeight() - in.top - in.bottom;

        p = new JPanel();
        p.setLayout(null);
        p.setBackground(Color.WHITE);
        fr.add(p, BorderLayout.CENTER);

        tf = new JTextField();
        tf.setHorizontalAlignment(tf.LEFT);
        tf.addActionListener(this);
        tf.setBounds(0, 400, 300, height-400);
        p.add(tf);

        b = new JButton("Send");
        b.setBounds(300, 400, width-300, height-400);
        b.addActionListener(this);
        p.add(b);

        p.validate();
        fr.validate();

        p.repaint();
        fr.repaint();

        for(int i=0;i<lines;i++) {
            l[i] = new JLabel("");
            l[i].setHorizontalAlignment(l[i].LEFT);
            l[i].setBounds(0, 400*i/lines, 500, 400/lines);
            p.add(l[i]);
        }
    }

    public void showString(String text) {
        if (text.equals("")) return;
        for(int i=0;i<lines-1;i++) {
            l[i].setText(l[i+1].getText());
        }
        l[lines-1].setText(text);
    }

    public void actionPerformed(ActionEvent ae) {
        String text = tf.getText();
        try {
            showString(text);
            out.write(text);
            out.flush();
            tf.setText("");
        } catch (IOException ioe) {

        }
    }
}

The readLine() function waits for the end of line. readLine()函数等待行尾。 In your chat class, you are never giving it an end of line while writing to the output stream. 在您的聊天类中,在写入输出流时,您永远不要给它结尾。 And so both server and client waits up at in.readLine() for an end of line character so as to complete reading a single line. 因此,服务器和客户端都在in.readLine()中等待行尾字符,从而完成了对单行的读取。 You need to give it an end of line character after each line you write to the output stream. 在写入输出流的每一行之后,都需要给它一个行尾字符。 Only flushing it will not suffice. 仅冲洗它是不够的。

So simply modify this part in your Chat class. 因此,只需在您的聊天类中修改此部分。

Old code 旧代码

        out.write(text);
        out.flush();

New code 新密码

        out.write(text);
        out.write('\n');
        out.flush();

Rest all of the code is working absolutely fine. 其余所有代码都可以正常工作。 Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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