Java:客户端 - 服务器,聊天广播

时间:2014-04-26 07:20:02

标签: java client-server chat

我正在为大学项目开发​​Client-Server聊天程序,而且我的编程背景很少。我已经完成了3个课程: ChatClient ChatServer ChatServerThread 。我现在可以连接多个客户端并随时与服务器通信。

虽然我遇到的最大困难之一是:"从1个客户端输入的任何消息都会发送给所有其他客户端"并且还应该显示发送和接收的消息"。

我花了几天的时间才试图让这些额外的功能正常工作,但没有运气。

我一直在阅读并环顾四周,但是我很难将在线示例应用到我的工作中。我已经读过我应该创建一个套接字列表,然后遍历列表并将数据发送给列表中的每个人,这在我的脑海中是有意义的但是当我尝试实现它时让我头疼。任何有关这方面的帮助将非常感激。如果有人能给我一些关于如何加密发送数据的信息,那就加分了。

ChatClient

import java.net.*;
import java.io.*;

public class ChatClient {
    private Socket socket = null;
    private DataInputStream console = null;
    private DataOutputStream streamOut = null;
    private String myName = null;
    private BufferedReader StreamIn = null;
    private String response = null;

    public ChatClient(String serverName, int serverPort) {
        try {
            console = new DataInputStream(System.in);
            System.out.println("What is your name?");
            myName = console.readLine();
            System.out.println(myName + " <" + InetAddress.getLocalHost() + "> ");
        } catch (IOException ioe) {
            System.out.println("Unexpected exception: " + ioe.getMessage());
        }
        System.out.println("Establishing connection. Please wait ...");
        try {
            socket = new Socket(serverName, serverPort);
            System.out.println("Connected: " + socket);
            StreamIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            streamOut = new DataOutputStream(socket.getOutputStream());
            streamOut.writeUTF(":" + myName + " <" + InetAddress.getLocalHost() + "> HAS JOINED");
            streamOut.flush();
        } catch (UnknownHostException uhe) {
            System.out.println("Host unknown: " + uhe.getMessage());
        } catch (IOException ioe) {
            System.out.println("Unexpected exception: " + ioe.getMessage());
        }
        String line = "";
        while (!line.equals(".bye")) {
            try {
                line = console.readLine();
                streamOut.writeUTF(myName + " <" + InetAddress.getLocalHost() + "> : " + line);
                streamOut.flush();

            } catch (IOException ioe) {
                System.out.println("Sending error: " + ioe.getMessage());
            }
        }
    }

    public void stop() {
        try {
            if (console != null) console.close();
            if (streamOut != null) streamOut.close();
            if (socket != null) socket.close();
        } catch (IOException ioe) {
            System.out.println("Error closing ...");
        }
    }

    public static void main(String args[]) {
        ChatClient client = null;
        if (args.length != 2)
            System.out.println("Usage: java ChatClient host port");
        else
            client = new ChatClient(args[0], Integer.parseInt(args[1]));
    }
}

的ChatServer

 import java.net.*;
import java.io.*;
import java.util.*;

public class ChatServer implements Runnable {
    private ServerSocket server = null;
    private Thread thread = null;
    private ChatServerThread client = null;
    private String clientSentence = null;
    private int peers = 0;
    private List clients = new ArrayList();
    final List sockets = new ArrayList();

    public ChatServer(int port) {
        try {
            System.out.println("Binding to port " + port + ", please wait  ...");
            server = new ServerSocket(port);
            System.out.println("Server started: " + server);
            start();
        } catch (IOException ioe) {
            System.out.println(ioe);
        }
    }

    public void run() {
        while (thread != null) {
            try {
                System.out.println("Waiting for a client ...");
                addThread(server.accept());
            } catch (IOException ie) {
                System.out.println("Acceptance Error: " + ie);
            }
        }
    }

    public void addThread(Socket socket) {
        System.out.println("Client accepted: " + socket);
        client = new ChatServerThread(this, socket);
        try {
            client.open();
            client.start();
        } catch (IOException ioe) {
            System.out.println("Error opening thread: " + ioe);
        }
    }

    public void start() {
        if (thread == null) {
            thread = new Thread(this);
            thread.start();
        }
    }

    public void stop() {
        if (thread != null) {
            thread.stop();
            thread = null;
        }
    }

    public void increment(String sentence) {
        peers++;
        String[] info = sentence.split(" ");
        String name = info[0].replace(":", "");
        System.out.println(name + " Has joined the room, we now have " + peers + " peer(s).");
        clients.add(name);
    }

    public Boolean isAllowed(String name, Socket socket) {
        try {
            String stringSearch = name;
            BufferedReader bf = new BufferedReader(new FileReader("allowed.txt"));
            int linecount = 0;
            String line = "";
            System.out.println("Searching for " + stringSearch + " in file...");
            while ((line = bf.readLine()) != null) {
                linecount++;
                String[] words = line.split(" ");

                for (String word : words) {
                    if (word.equals(stringSearch)) {
                        System.out.println("User is allowed");
                        registerSocket(socket);
                        return true;
                    }
                }
            }
            bf.close();
        } catch (IOException e) {
            System.out.println("IO Error Occurred: " + e.toString());
        }
        System.out.println("User is not allowed");
        return false;
    }

    public void showAll() {
        for (int i = 0; i < clients.size(); i++) {
            System.out.print(clients.get(i));
        }
    }

    public void registerSocket(Socket socket) {
        //socket = new DataOutputStream(socket.getOutputStream());   
        sockets.add(socket);
        for (int i = 0; i < sockets.size(); i++) {
            System.out.println(sockets.get(i));
        }
    }

    public static void main(String args[]) {
        ChatServer server = null;
        if (args.length != 1)
            System.out.println("Usage: java ChatServer port");
        else
            server = new ChatServer(Integer.parseInt(args[0]));
    }
}

ChatServerThread

import java.net.*;
import java.io.*;

public class ChatServerThread extends Thread {
    private Socket socket = null;
    private ChatServer server = null;
    private int ID = -1;
    private DataInputStream streamIn = null;
    private String clientSentence = null;
    public String newGuy = null;
    DataOutputStream streamOut = null;

    public ChatServerThread(ChatServer _server, Socket _socket) {
        server = _server;
        socket = _socket;
        ID = socket.getPort();
    }

    public void run() {
        System.out.println("Server Thread " + ID + " running.");
        while (true) {
            try {
                String sentence = streamIn.readUTF();
                //System.out.println(sentence);
                char c = sentence.charAt(0);
                String[] command = null;
                command = sentence.split(" ");
                String name = command[0].substring(1);

                System.out.println("Sending out: " + sentence + " via ");

                streamOut.writeBytes(sentence);

                if (c == ':') {
                    if (server.isAllowed(name, socket))
                        server.increment(sentence);
                    else {
                        close();
                    }
                }
            } catch (IOException ioe) {
            }
        }
    }

    public void open() throws IOException {
        streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
    }

    public void close() throws IOException {
        if (socket != null) socket.close();
        if (streamIn != null) streamIn.close();
    }
}

0 个答案:

没有答案