用Java用Socket链接两台计算机 [英] Link two computers with Socket in Java

查看:71
本文介绍了用Java用Socket链接两台计算机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Java编写的服务器和一个客户端,它们都可以在localhost或使用我的机器IP来工作,但是当我从本地网络中的另一台计算机告诉一个IP时,它会显示发生了异常:连接被拒绝:连接"!这是我的代码:

ChatClient.java

 程序包编程聊天;导入java.io.BufferedReader;导入java.io.DataOutputStream;导入java.io.File;导入java.io.IOException;导入java.io.InputStreamReader;导入java.net.Socket;导入java.net.UnknownHostException;导入java.util.Scanner;公共类ChatClient {专用套接字套接字;专用扫描仪控制台;私有DataOutputStream输出;专用的BufferedReader阅读器;公共ChatClient(字符串serverName,int serverPort){尝试 {System.out.println("LiveChat Client 1.1启动.");System.out.println(尝试在端口" + serverPort +"..."上连接到"+ serverName +"socket = new Socket(serverName,serverPort);System.out.println(成功!");控制台=新的Scanner(System.in);输出=新的DataOutputStream(socket.getOutputStream());reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));线程t1 =新线程(){@Override公共无效run(){字符串行=";while(!line.equals(.bye")){尝试 {System.out.print("me:");行= console.nextLine();output.writeUTF(line);output.flush();} catch(IOException e){e.printStackTrace();}}}};线程t2 =新线程(){@Override公共无效run(){字符串行=";尝试 {while(!(line = reader.readLine()).equals(.bye")){System.out.print("\ nhe:" +行+"\ nme:");}} catch(IOException e){e.printStackTrace();}}};t1.start();t2.start();} catch(UnknownHostException e){System.err.println(未知主机:" + e.getMessage());} catch(IOException e){System.err.println(发生异常:" + e.getMessage());} catch(Exception e){e.printStackTrace();System.exit(-1);}}@SuppressWarnings({未使用",资源"})公共静态void main(String [] args)引发IOException {File hostsFile = new File("hosts.dat");if(!hostsFile.exists()){hostsFile.createNewFile();FileController.writeFile(hostsFile.getPath(),"localhost \ n");}字符串hosts = FileController.loadFile("hosts.dat");String [] h = hosts.split("\ n");System.out.println(按主机号选择主机,或插入一个新主机.");System.out.println(当前可用的主机:");for(int i = 0; i< h.length; i ++){System.out.println(i +:" + h [i]);}System.out.print(请提供服务器的IP地址:");Scanner s =新的Scanner(System.in);字符串hostName = s.nextLine();if(isInteger(hostName)){int i = Integer.parseInt(主机名);hostName = h [i];} 别的 {FileController.writeFile(hostsFile.getPath(),hostName +"\ n");}ChatClient客户=新的ChatClient("localhost",9081);}私人静态布尔isInteger(String str){布尔值=否;尝试 {Integer.parseInt(str);是= true;} catch(Exception e){是= false;}返回是}} 

ChatServer.java

 程序包编程聊天;导入java.io.BufferedInputStream;导入java.io.DataInputStream;导入java.io.IOException;导入java.io.PrintStream;导入java.net.ServerSocket;导入java.net.Socket;公共类ChatServer {专用Socket []套接字;私有ServerSocket服务器;私人DataInputStream [] ins;私人PrintStream []输出;私有字符串ln1;私有字符串ln2;公共ChatServer(int端口){尝试 {System.out.println("LiveChat Server 0.9启动.");System.out.println(正在尝试打开端口" +端口+"...");服务器=新的ServerSocket(端口);System.out.println("Server" + server.getInetAddress().getHostName()+已成功启动!");System.out.println(正在实例化输入和输出流...");ins =新的DataInputStream [2];outs =新的PrintStream [2];System.out.println(成功!");System.out.println(正在实例化套接字...");sockets =新的Socket [2];System.out.println(成功!");System.out.println(正在等待套接字1连接...");套接字[0] = server.accept();System.out.println(成功!");System.out.println(正在等待套接字2连接...");套接字[1] = server.accept();System.out.println(成功!");System.out.println(正在打开输入和输出流...");打开();System.out.println(成功!");System.out.println(正在初始化输入字符串...");ln1 =";ln2 =";System.out.println(成功!");线程r1 =新线程(){@Override公共无效run(){尝试 {while(!ln1.equals(.bye")){ln1 = ins [0] .readUTF();System.out.println("1:" + ln1);outs [1] .println(ln1);}System.out.println(套接字1断开连接!");sockets [0] .close();} catch(IOException e){e.printStackTrace();}}};线程r2 =新线程(){@Override公共无效run(){尝试 {while(!ln2.equals(.bye")){ln2 = ins [1] .readUTF();System.out.println("2:" + ln2);outs [0] .println(ln2);}System.out.println(套接字2断开连接!");sockets [1] .close();} catch(IOException e){e.printStackTrace();}}};r1.start();r2.start();} catch(Exception e){e.printStackTrace();}}public void open()引发IOException {ins [0] = new DataInputStream(new BufferedInputStream(sockets [0] .getInputStream()));ins [1] = new DataInputStream(new BufferedInputStream(sockets [1] .getInputStream()));outs [0] =新的PrintStream(sockets [0] .getOutputStream());outs [1] =新的PrintStream(sockets [1] .getOutputStream());}@SuppressWarnings(未使用")公共静态void main(String [] args){ChatServer chat =新的ChatServer(9081);}} 

请,有人可以帮助我吗?

解决方案

使用服务器的本地IP地址代替本地主机"

  ChatClient客户端=新的ChatClient("localhost",9081); 

您的服务器位于另一台计算机上,如果服务器和客户端都在一台计算机上,则它可以正常工作.

(如何找到我的本地(内部)IP地址?)

未通过转发路由器上的端口号将路由器配置为不接受客户端和服务器之间的此连接肯定会导致此错误,因此应该执行此操作.

(如何在路由器上设置端口转发,具体取决于路由器类型)

(您也可以查看此视频)

I have a server and a client in Java, both work in localhost or with my machine IP, but when I tells a IP from another computer in my local network, it tells "Exception occurred: Connection refused: connect"! Here is my code:

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);
    }
}

Please, someone can help me?

解决方案

Use server's local IP address instead of "localhost"

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

your server is on different machine, it works if both server and client are on one machine.

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

Edit:

Not configuring router to accept this connection between client and server by forwarding port number on router definitely could cause this error, so you should do this.

(How to Set Up Port Forwarding on a Router, it differs according to router type)

(You could check also this video)

这篇关于用Java用Socket链接两台计算机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆