使用java和套接字的简单聊天程序

我在 Java中使用套接字时遇到问题:服务器没有响应,也没有抛出异常.

服务器代码

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

class Server {
    public static void main(String args[]) {
        final int time = 75;
        //boolean CHAT_SESSION_ALIVE = false; 
        int port = 9999;

        try {
            System.out.println("Starting chat server using the port : " + port);
            ServerSocket srvr = new ServerSocket(port);
            Socket skt = srvr.accept();
            System.out.println("Server has connected with client         " + skt.getInetAddress());
            //CHAT_SESSION_ALIVE = true;

            PrintWriter out = new PrintWriter(skt.getOutputStream(),true);
            BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));

            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            if (in.ready()) {
                                String msg = in.readLine();
                                System.out.println("receive message: '" + msg + "'");
                                Thread.sleep(time);
                            }
                        } catch (Exception e) {
                            System.out.println(e);
                        }
                    }
                }
            }).start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(time);
                            String msg = new Scanner(System.in).nextLine();
                            System.out.println("Sending message: '" + msg + "'");
                            out.print(msg);
                        } catch (Exception e) {
                            System.out.println(e);
                        }
                    }
                }
            }).start();

            //in.close();
            //out.close();
            //skt.close();
            //srvr.close();
        } catch (Exception e) {
            System.out.print(e);
        }
    }
}

客户代码

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

class Client {
    public static void main(String args[]) {
        final int time = 75;
        //boolean CHAT_SESSION_ALIVE = false;
        int port = 9999;
        String hostIP = "127.0.0.1";

        try {
            Socket skt = new Socket(hostIP,port);
            System.out.println("Client has connected with server " + hostIP + ":" + port);
            //CHAT_SESSION_ALIVE = true;

            PrintWriter out = new PrintWriter(skt.getOutputStream(),true);
            BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));

            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            if (in.ready()) {
                                String msg = in.readLine();
                                System.out.println("receive message: '" + msg + "'");
                                Thread.sleep(time);
                            }
                        } catch (Exception e) {
                            System.out.println(e);
                        }
                    }
                }
            }).start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            String msg = new Scanner(System.in).nextLine();
                            System.out.println("Sending message: '" + msg + "'");
                            out.print(msg);
                            Thread.sleep(time);
                        } catch (Exception e) {
                            System.out.println(e);
                        }
                    }
                }
            }).start();

            //in.close();
            //out.close();
            //skt.close();
        } catch (Exception e) {
            System.out.print(e);
        }
    }
}

服务器输出

Starting chat server using the port : 9999
Server has connected with client /127.0.0.1

客户输出

Client has connected with server 127.0.0.1:9999
simple message
Sending message: ‘simple message’

请解释服务器无法正常工作的原因.

解决方法

Scanner.nextLine返回没有新行delim的行.服务器正在使用BufferedReader.readLine,它需要一个新行(如果没有收到,则可能会阻塞).解决方案:在发送消息时附加分隔符.如果使用print,则必须明确刷新:
out.print(msg + "\n"); 
out.flush();//explicitly flush the stream

或者使用println方法让它为你添加新行(并使用传递给PrintWriter构造函数的autoflush true标志):

out.println(msg);//auto flushing

相关文章

ArrayList简介:ArrayList 的底层是数组队列,相当于动态数组。与 Java 中的数组相比,它的容量能动态增...
一、进程与线程 进程:是代码在数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位。 线程...
本文为博客园作者所写: 一寸HUI,个人博客地址:https://www.cnblogs.com/zsql/ 简单的一个类...
#############java面向对象详解#############1、面向对象基本概念2、类与对象3、类和对象的定义格式4、...
一、什么是异常? 异常就是有异于常态,和正常情况不一样,有错误出错。在java中,阻止当前方法或作用域...
Collection接口 Collection接口 Collection接口 Collection是最基本的集合接口,一个Collection代表一组...