简体   繁体   English

如何通过套接字发送PM

[英]How can I send PM thru Socket

I've been trying to send private message to a client(from sendPrivate method) but it still don't work. 我一直在尝试将私人消息发送到客户端(通过sendPrivate方法),但仍然无法正常工作。 Can I have any suggestion here? 请问我有什么建议吗? (My sendToAllMethod works). (我的sendToAllMethod有效)。 Here is my code so far. 到目前为止,这是我的代码。 Thanks in advance guys :) 在此先感谢大家:)

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

public class TestServer extends Thread {
    private Socket clientSocket;
    protected static String inputLine;
    public static ArrayList < Socket > ConnectionArray = new ArrayList < Socket > ();
    public static ArrayList < String > CurrentUsers = new ArrayList < String > ();
    String Sender;
    String Receiver;

    final static int PORT = 256;


    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(PORT);
            System.out.println("Connection Socket Created");
            try {
                while (true) {
                    System.out.println("Waiting for Connection");
                    Socket sock = serverSocket.accept();
                    ConnectionArray.add(sock);
                    System.out.println("Client connected from: " + sock.getLocalAddress().getHostName());
                    new TestServer(sock);
                }
            } catch (IOException e) {
                System.err.println("Accept failed.");
                System.exit(1);
            }
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + PORT);
            System.exit(1);
        } finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                System.err.println("Could not close port: 10008.");
                System.exit(1);
            }
        }
    }

    private TestServer(Socket inSock) {
        clientSocket = inSock;
        start();
    }

    public void run() {
        System.out.println("New Communication Thread Started");
        //System.out.println ("Client connected from: " + sock.getLocalAddress().getHostName());

        try {
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            while (true) {

                for (int i = 1; i <= TestServer.ConnectionArray.size(); i++) {
                    Socket TEMP_SOCK = (Socket) TestServer.ConnectionArray.get(i - 1);
                    if (clientSocket == TEMP_SOCK)
                        try {
                            Sender = TestServer.CurrentUsers.get(i - 1);
                        } catch (Exception e) {}

                }
                inputLine = in .readLine();
                System.out.println("Server: " + inputLine);
                getCommand(inputLine);

                if (inputLine.equals("EXIT"))
                    break;
            }
            out.close(); in .close();
            clientSocket.close();
        } catch (IOException e) {
            System.err.println("Problem with Communication Server");
            System.exit(1);
        }
    }

    public void addUsername(String inputName) throws IOException {
        CurrentUsers.add(inputName);

        for (int i = 1; i <= TestServer.ConnectionArray.size(); i++) {
            Socket TEMP_SOCK = (Socket) TestServer.ConnectionArray.get(i - 1);
            PrintWriter OUT = new PrintWriter(TEMP_SOCK.getOutputStream());
            OUT.println("Current Users: " + CurrentUsers);
            OUT.flush();
        }
    }

    public void sendToAll(String input) throws IOException {

        for (int i = 1; i <= TestServer.ConnectionArray.size(); i++) {
            Socket TEMP_SOCK = (Socket) TestServer.ConnectionArray.get(i - 1);
            if (clientSocket != TEMP_SOCK) {
                PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream(), true);
                TEMP_OUT.println(Sender + ": " + input);
                TEMP_OUT.flush();
                System.out.println("Sending to: " + TEMP_SOCK.getLocalAddress().getHostName());
            }
        }

    }

    public void sendPrivate(String inputName, String inputMsg) throws IOException {
        Socket TEMP_SOCK = null;
        for (int a = 1; a <= TestServer.CurrentUsers.size(); a++) {
            String Receiver = TestServer.CurrentUsers.get(a - 1);
            if (inputName == (Receiver)); {
                System.out.println("Found username!!!");
                TEMP_SOCK = (Socket) TestServer.ConnectionArray.get(a - 1);
            }
        }
        PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream());
        TEMP_OUT.println("[PM] " + Sender + " :" + inputMsg);
        TEMP_OUT.flush();
    }

    public void getCommand(String inputCmd) throws IOException {
        String str = inputCmd;
        String[] splitStr = str.trim().split("\\s+");

        if (splitStr[0].equalsIgnoreCase("REG")) {
            System.out.println("Registering");
            StringBuffer result = new StringBuffer();
            for (int y = 1; y < splitStr.length; y++) {
                result.append(splitStr[y]);
                result.append(" ");
            }
            String joinedStr = result.toString();
            System.out.println("Registering Name ---> " + joinedStr);
            addUsername(joinedStr);
        } else if (splitStr[0].equalsIgnoreCase("MSG")) // SEND TO ALL
        {
            System.out.println("Sending to ALL");
            StringBuffer result = new StringBuffer();
            for (int y = 1; y < splitStr.length; y++) {
                result.append(splitStr[y]);
                result.append(" ");
            }
            String joinedStr = result.toString();
            System.out.println("Sending---> " + joinedStr);
            sendToAll(joinedStr);
        } else if (splitStr[0].equalsIgnoreCase("PMSG")) // SEND PRIVATE
        {
            System.out.println("Sending Private Message");
            StringBuffer result = new StringBuffer();
            for (int y = 2; y < splitStr.length; y++) {
                result.append(splitStr[y]);
                result.append(" ");
            }
            String joinedStr = result.toString();
            System.out.println("Sending---> " + joinedStr);
            String pvtMsg = splitStr[1];
            sendPrivate(pvtMsg, joinedStr);
        } else if (splitStr[0].equalsIgnoreCase("EXIT")) {
            Socket TEMP_SOCK = clientSocket;
            PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream(), true);
            TEMP_OUT.println("Bye bye");
            TEMP_OUT.flush();
        } else {
            Socket TEMP_SOCK = clientSocket;
            PrintWriter OUT = new PrintWriter(TEMP_SOCK.getOutputStream());
            OUT.println("Invalid Input");
            OUT.flush();
        }
    }

}
inputName == (Receiver)

应该是:

inputName.equals(Reciever)

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

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