一个简单的命令行聊天程序

今天再复习java网络和多线程的一些知识,就随手写了一个简单的命令行的聊天程序,以下是代码,仅供参考。


TestTcpServer.java

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TestTcpServer {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(8888);
        Socket socket = serverSocket.accept();
        System.out.println("Welcome, Client");
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        Scanner in = new Scanner(System.in);

        String myWords = null;
        Listen listen = new Listen(dis, "Client: ");
        Thread thread = new Thread(listen);
        thread.start();

        do {
            myWords = in.nextLine();
            dos.writeUTF(myWords);
            if (myWords.equals("bye")) {
                break;
            }
        } while (true);

        dos.close();
        dis.close();
        socket.close();
    }
}

TestTcpClient.java

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class TestTcpClient {

    public static void main(String[] args) throws UnknownHostException,
            IOException {
        Socket socket = new Socket("127.0.0.1", 8888);
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        Scanner in = new Scanner(System.in);

        String myWords;
        Listen listen = new Listen(dis, "Server: ");
        Thread thread = new Thread(listen);
        thread.start();

        do {
            myWords = in.nextLine();
            dos.writeUTF( myWords);
            if (myWords.equals("bye")) {
                break;
            }       
        } while (true);

        dis.close();
        dos.close();
        socket.close();
    }
}

Listen.java用于监听对方传过来的消息

import java.io.DataInputStream;

class Listen implements Runnable {

    private DataInputStream dis;
    private boolean flag = true;
    private final String prefix;
    private String words;

    Listen (DataInputStream dis, String prefix) {
        this.dis = dis;
        this.prefix = prefix;
    }

    public void run() {
        while (flag) {
            try {
                words = dis.readUTF();
                if (words.equals("bye")) {
                    flag = false;
                }
                System.out.println(prefix + words);
            } catch (Exception e) {
                flag = false;
            }
        }
    }

    public boolean getFlag() {
        return flag;
    }

    public void setFlag(boolean b) {
        flag = b;
    }
}

只是为了简单的实现功能,写的不是很完善,大家多多指正。

你可能感兴趣的:(java)