为什么我的套接字没有恢复消息?

时间:2015-08-30 09:26:50

标签: java sockets

我正在尝试学习如何在下学期之前使用Java套接字。我写了这个程序,它应该接受来自发件人的邮件并将邮件发送给收件人。您可以通过写入已连接的客户端的名称来指定接收方,如果客户端未连接,则服务器将通过发送消息“DISCONNECTED”进行响应。但由于某种原因,邮件不会发送给收件人。我仍然可以将消息发送给发件人。这是寻求这种帮助的正确论坛吗?

这是我的客户端类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class MyTestClient {

static int port = 0;
static String ip = "";
static String name = "";

public static void main(String args[] ) {

    if(args.length == 3) {

        try{
            port = Integer.parseInt(args[1]);
        } catch(NumberFormatException e) {
            System.out.println("Usage: Java MyTestClient <ip> <port> <name>");
            System.exit(0);
        }
        ip = args[0];
        name = args[2];

    } else {

        System.out.println("Usage: Java MyTestClient <ip> <port> <name>");
        System.exit(0);

    }

    try {
        Socket socket = new Socket(ip, port);

        new Thread(new MessageHandler(socket)).start();
        new Thread(new InputHandler(socket)).start();

    } catch (IOException e) {
        System.out.println("Could not connect to: " + ip + " : " + port); 
        System.exit(0);
    }
}

public static class MessageHandler implements Runnable {

    Socket socket;

    public MessageHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        PrintWriter out = null;
        BufferedReader in = null;

        try {
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }catch(IOException e) {
            e.printStackTrace();
        }

        String fromServer;
        try {
            while ((fromServer = in.readLine()) != null) {
                System.out.println(fromServer);
                fromServer.trim();
                if(fromServer.contains(" ")) {
                    String split[] = fromServer.split(" ", 2);
                    System.out.println(split.length == 2 ? split[1] + " Is a two part message" : "Strange message");
                } else {
                    if(fromServer.equals("NAME")) {
                        System.out.println("Server asks for name | gives given name to server");
                        out.println(name);
                    }
                    if(fromServer.equals("SUCCESS")) {
                        System.out.println("Message succesfully sent");
                    }
                    if(fromServer.equals("ERROR")) {
                        System.out.println("Something went wrong when sending the message");
                    }
                    if(fromServer.equals("OCCUPIED")) {
                        System.out.println("Name was already used. Start the program with another name");
                        socket.close();
                        System.exit(0);
                    }
                    if(fromServer.equals("DISCONNECTED")) {
                        System.out.println("The reciever was not connected");
                    }
                    if(fromServer.equals("REGISTERED")) {
                        System.out.println("Successfully logged in to server");
                    }
                }
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

}

public static class InputHandler implements Runnable {

    Socket socket;

    public InputHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        String fromUser = null;

        PrintWriter out = null;
        try {
            out = new PrintWriter(socket.getOutputStream(), true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedReader kbi = new BufferedReader(new InputStreamReader(System.in));

        try {
            while ((fromUser = kbi.readLine()) != null) {
                out.println(fromUser);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

}

这是我的服务器类

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

public class MyServer {

    public static int port;
    public static int maxConnections;
    public static final String NAME = "Server";
    private static Map<String, Socket> socketsMap = new HashMap<>();

    public static void main(String args[]) {

        if(args.length == 2) {
            try{
                port = Integer.parseInt(args[0]); 
                maxConnections = Integer.parseInt(args[1]); 
            }catch(Exception e){
                System.out.println("Usage: Java Myserver <port> <maxConnections>");
                System.exit(0);
            }
        } else {
            System.out.println("Usage: Java Myserver <port> <maxConnections>");
            System.exit(0);
        }

        new Thread(new ConnectionHandler(port, maxConnections)).start();

    }

    public static class ConnectionHandler implements Runnable {

        private ServerSocket server;
        private Socket socket = null;
        public int currentSocket = 0;
        public int port = 0;
        public int maxConnections = 0;

        public ConnectionHandler(int port, int maxConnections) {
            this.maxConnections = maxConnections;
            this.port = port;
        }

        @Override
        public void run() {
            try {
                server = new ServerSocket(7777);
            } catch (IOException e1) {
                System.out.println("Server could not connect to port: " + port);
                e1.printStackTrace();
                System.exit(0);
            }

            while(currentSocket++ < maxConnections) {
                try {
                    socket = server.accept();
                    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    out.println("NAME");
                    String message;
                    while((message = in.readLine()) != null) {
                        if(!socketsMap.containsKey(message) || message.equals("SERVER")) {
                            out.println("REGISTERED");
                            socketsMap.put(message, socket);
                            System.out.println(message + " has logged on server");

                            new Thread(new SocketHandler(socketsMap.get(message))).start();

                        } else {
                            out.println("OCCUPIED");
                            System.out.println(socket.getInetAddress().toString() + " has tried to login with existing name " + message);
                            socket.close();
                            currentSocket--;
                        }
                        socket = null;
                        break;
                    }
                } catch (IOException e) {
                    System.out.println("Something went wrong with client connection");
                }
            }


        }

    }

    public static class SocketHandler implements Runnable {

        Socket socket = null;

        public SocketHandler(Socket socket) {

            this.socket = socket;

        }

        @Override
        public void run() {

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

                String input;
                while((input = in.readLine() ) != null) {
                    String[] info = input.split(" ", 2);

                    if(info.length != 2){
                        System.out.println("Message computed wrong");
                        respond.println("ERROR");
                        break;
                    }
                    if(info[0].equals("SERVER")) {

                        //TODO: Write a server command handler class

                    } else if ( socketsMap.containsKey(info[0]) ){

                        Socket reciever = socketsMap.get(info[0]);
                        PrintWriter out = new PrintWriter(reciever.getOutputStream());
                        respond.println("SUCCESS");
                        System.out.println(info[0] + " send the message: "+ info[1]);
                        out.println("MESSAGE" + " " + info[1]);
                        break;

                    } else {
                        System.out.println("Reciever is not connected");
                        respond.println("DISCONNECTED");
                    }
                }
            }catch(IOException e) {
                e.printStackTrace();
            }
        }
    }

}

也许你可以在电脑上运行它,看看我的意思?

1 个答案:

答案 0 :(得分:-1)

 @Override
        public void run() {
            try {
                server = new ServerSocket(7777);
            } catch (IOException e1) {
                System.out.println("Server could not connect to port: " + port);
                e1.printStackTrace();
                System.exit(0);
            }

将上面的代码更改为

 @Override
        public void run() {
            try {
                server = new ServerSocket(port);
            } catch (IOException e1) {
                System.out.println("Server could not connect to port: " + port);
                e1.printStackTrace();
                System.exit(0);
            }