【问题标题】:Link two computers with Socket in Java用Java中的Socket连接两台计算机
【发布时间】:2017-03-30 15:20:42
【问题描述】:

我有一个 Java 的服务器和一个客户端,都在本地主机或我的机器 IP 中工作,但是当我从本地网络中的另一台计算机告诉 IP 时,它告诉“发生异常:连接被拒绝:连接”!这是我的代码:

ChatClient.java

package programmingchat;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ChatClient {

    private Socket socket;
    private Scanner console;
    private DataOutputStream output;
    private BufferedReader reader;

    public ChatClient(String serverName, int serverPort) {
        try {
            System.out.println("LiveChat Client 1.1 start.");
            System.out.println("Trying to connect to " + serverName + " on port " + serverPort + "...");
            socket = new Socket(serverName, serverPort);
            System.out.println("Success!");

            console = new Scanner(System.in);
            output = new DataOutputStream(socket.getOutputStream());
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            Thread t1 = new Thread(){
                @Override
                public void run() {
                    String line = "";

                    while(!line.equals(".bye")) {
                        try {
                            System.out.print("me: ");
                            line = console.nextLine();
                            output.writeUTF(line);
                            output.flush();
                        } catch(IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };

            Thread t2 = new Thread(){
                @Override
                public void run() {
                    String line = "";

                    try {
                        while(!(line = reader.readLine()).equals(".bye")) {
                            System.out.print("\nhe: " + line + "\nme: ");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            t1.start();
            t2.start();
        } catch(UnknownHostException e) {
            System.err.println("Unknown host: " + e.getMessage());
        } catch(IOException e) {
            System.err.println("Exception ocurred: " + e.getMessage());
        } catch(Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    @SuppressWarnings({ "unused", "resource" })
    public static void main(String[] args) throws IOException {
        File hostsFile = new File("hosts.dat");

        if(!hostsFile.exists()) {
            hostsFile.createNewFile();
            FileController.writeFile(hostsFile.getPath(), "localhost\n");
        }

        String hosts = FileController.loadFile("hosts.dat");
        String[] h = hosts.split("\n");

        System.out.println("Select host by it number, or insert a new one.");
        System.out.println("Currently avaliable hosts: ");

        for(int i = 0; i < h.length; i++) {
            System.out.println(i + ": " + h[i]);
        }

        System.out.print("Please provide the IP Address of the server: ");
        Scanner s = new Scanner(System.in);
        String hostName = s.nextLine();

        if(isInteger(hostName)) {
            int i = Integer.parseInt(hostName);
            hostName = h[i];
        } else {
            FileController.writeFile(hostsFile.getPath(), hostName + "\n");
        }

        ChatClient client = new ChatClient("localhost", 9081);
    }

    private static boolean isInteger(String str) {
        boolean is = false;

        try {
            Integer.parseInt(str);
            is = true;
        } catch(Exception e) {
            is = false;
        }

        return is;
    }
}

ChatServer.java

package programmingchat;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {

    private Socket[] sockets;
    private ServerSocket server;
    private DataInputStream[] ins;
    private PrintStream[] outs;

    private String ln1;
    private String ln2;

    public ChatServer(int port) {
        try {
            System.out.println("LiveChat Server 0.9 start.");
            System.out.println("Trying to open port " + port + "...");
            server = new ServerSocket(port);
            System.out.println("Server " + server.getInetAddress().getHostName() + " successfully started!");
            System.out.println("Instantiating input and output streams...");
            ins = new DataInputStream[2];
            outs = new PrintStream[2];
            System.out.println("Success!");
            System.out.println("Instantiating sockets...");
            sockets = new Socket[2];
            System.out.println("Success!");
            System.out.println("Waiting socket 1 to connect...");
            sockets[0] = server.accept();
            System.out.println("Success!");
            System.out.println("Waiting socket 2 to connect...");
            sockets[1] = server.accept();
            System.out.println("Success!");
            System.out.println("Opening input and output streams...");
            open();
            System.out.println("Success!");
            System.out.println("Initializing input strings...");
            ln1 = "";
            ln2 = "";
            System.out.println("Success!");

            Thread r1 = new Thread() {
                @Override
                public void run() {
                    try {
                        while(!ln1.equals(".bye")) {
                            ln1 = ins[0].readUTF();
                            System.out.println("1: " +ln1);
                            outs[1].println(ln1);
                        }

                        System.out.println("Socket 1 disconnect!");
                        sockets[0].close();
                    } catch(IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            Thread r2 = new Thread() {
                @Override
                public void run() {
                    try {
                        while(!ln2.equals(".bye")) {
                            ln2 = ins[1].readUTF();
                            System.out.println("2: " + ln2);
                            outs[0].println(ln2);
                        }

                        System.out.println("Socket 2 disconnect!");
                        sockets[1].close();
                    } catch(IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            r1.start();
            r2.start();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void open() throws IOException {
        ins[0] = new DataInputStream(new BufferedInputStream(sockets[0].getInputStream()));
        ins[1] = new DataInputStream(new BufferedInputStream(sockets[1].getInputStream()));
        outs[0] = new PrintStream(sockets[0].getOutputStream());
        outs[1] = new PrintStream(sockets[1].getOutputStream());
    }

    @SuppressWarnings("unused")
    public static void main(String[] args) {
        ChatServer chat = new ChatServer(9081);
    }
}

拜托,有人可以帮助我吗?

【问题讨论】:

    标签: java sockets server client connect


    【解决方案1】:

    使用服务器的本地 IP 地址而不是“localhost”

    ChatClient client = new ChatClient("localhost", 9081);
    

    您的服务器在不同的机器上,如果服务器和客户端都在一台机器上,它就可以工作。

    (How do I find my local (internal) IP address?)

    编辑:

    没有通过在路由器上转发端口号来配置路由器接受客户端和服务器之间的这种连接肯定会导致这个错误,所以你应该这样做。

    (How to Set Up Port Forwarding on a Router,根据路由器类型不同)

    (You could check also this video)

    【讨论】:

    • 对不起我的错误,但这是测试版本,做其他操作,行是:“ChatClient client = new ChatClient(hostName, 9081);”
    • 没有。它告诉同样的“连接被拒绝:连接”错误。
    • 您是否在路由器上转发了“9081”端口?
    • 不,我不知道什么是“转发端口”。
    • 我对我的回答进行了编辑以澄清这个问题,希望对您有所帮助。
    猜你喜欢
    • 2019-08-09
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    相关资源
    最近更新 更多