1

几天前我已经开始学习 Java 套接字编程。我在某个网站上找到了此代码,用于将文件从服务器传输到多个客户端(多线程,使用线程池)。

当我使用环回接口(127.0.0.1)运行此应用程序时,它工作正常,文件被传输到目标文件夹。但是当我将服务器电脑(192.168.1.2)连接到客户端电脑(192.168.1.3)时,出现异常并说

"Could not establish I/O for IP: <ipaddress of client> <port number>"

客户端和服务器端用网线连接好,互相ping通。他们之间没有防火墙。我对网站和 Java 套接字的初学者非常陌生。

谁能帮我调试或理解错误?

Client Side Code: 2 Java files
myfileclient.java // First File

import java.io.*;
import javax.swing.*;

public class myfileclient {

/**
 * @param args
 * @throws IOException 
 * @throws InterruptedException 
 */
public static void main(String[] args) throws IOException, InterruptedException {

    JFileChooser chooser = new JFileChooser();
    chooser.showOpenDialog(null);
    File file = chooser.getSelectedFile();
    String fileName = file.getName();
    //System.out.println("You have selected: " + filename);


    String serverAddress= "127.0.0.1";
    int serverPort=  4444;
    //String fileName = "D:\\a.pdf";


    //Create Socket
    System.out.println("client >Creating Socket to " + serverAddress + ":" + serverPort);
    JOptionPane.showMessageDialog(null,"Client: Connecting to: " + serverAddress + serverPort + "\nClient Connecting....." + "\nClient Requesting file : " + fileName ,"Success",JOptionPane.PLAIN_MESSAGE);
    SocketHandling client = new SocketHandling(serverAddress, serverPort);

    //Connect
    System.out.println("client >Connecting");
    client.connect();

    //File request
    System.out.println("client >Requesting file : " + fileName);

    client.requestFile("D:\\a.pdf");

    //Close all
    System.out.println("client >Close Connection");
    client.close();
}

}

SocketHandling.java // Second File

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JOptionPane;

public class SocketHandling {

    private Socket client;
    private PrintWriter socketWriter;
    private BufferedReader socketReader;
    public String destIpAddress;
    public int destPort;

    public SocketHandling(String destIpAddress, int destPort) {



        this.destIpAddress = destIpAddress;
        this.destPort = destPort;
    }

    public void connect() {

        try {
            //Create socket
            client = new Socket(this.destIpAddress,this.destPort);


            //Create read/write buffers for socket
            socketReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            socketWriter = new PrintWriter(client.getOutputStream(), true);

        } catch (UnknownHostException e) {
            System.err.println("Unkown host: " + destIpAddress);
        } catch (IOException e) {
            System.out.println("Could not establish I/O for IP: "+ destIpAddress + " on port: " + destPort);
            JOptionPane.showMessageDialog(null,"Could not establish I/O for IP: "+ destIpAddress + " on port: " + destPort,"Error",JOptionPane.PLAIN_MESSAGE);
        }
    }

    public void requestFile(String filename) throws IOException {

        //Timers
        long start = System.currentTimeMillis();
        int bytesRead;
        int current = 0;

        //Hard coded temporary file size 
        int filesize=7000000; 

        //Send File Name to server
        socketWriter.println(filename);
        socketWriter.flush();

        //Get n and m
        String message = (String)socketReader.readLine();

        //Split string up
        String[] tokens = message.split("[,]");
        int ConnectionCounter = Integer.parseInt(tokens[0]);
        int FileCounter = Integer.parseInt(tokens[1]);


        if(FileCounter >= 0){
            //File exists
            System.out.println("client >File " + filename + " was found at the serve"); 
            System.out.println("client >Server handled " + ConnectionCounter + " requests, " + FileCounter + " request were successsful.");
            //Receive file
            System.out.println("client >Downloading file " + filename);


            byte [] mybytearray  = new byte [filesize];
            InputStream is = client.getInputStream();
            FileOutputStream fos = new FileOutputStream("D:\\copy.pdf"); //Files Added to Download directory 
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesRead = is.read(mybytearray,0,mybytearray.length);
            current = bytesRead;

            do {
                bytesRead =
                        is.read(mybytearray, current, (mybytearray.length-current));
                if(bytesRead >= 0) current += bytesRead;
            } while(bytesRead > -1);

            bos.write(mybytearray, 0 , current);
            bos.flush();
            long end = System.currentTimeMillis();
            System.out.println("client >Download complete (" + (end-start) + "ms)");
            JOptionPane.showMessageDialog(null,"File:" + filename + " was found at the Server\nServer handled " + ConnectionCounter + "requests" + FileCounter + " requests were successsful!!\nDownloading file.....\nDownload complete!! (" + (end-start) + "ms) ","Success",JOptionPane.PLAIN_MESSAGE);
            bos.close();

        }else{
            //Files does not exists
            //System.out.println("client >File " + filename + " was not found at the serve");       
            System.out.println("client >Connection Counter : " + ConnectionCounter + "   File Counter : " + FileCounter);
            JOptionPane.showMessageDialog(null,"File " + filename + " was not found at the Server ","Error",JOptionPane.PLAIN_MESSAGE);
        }
    }

    public void close() {
        try {
            //Closes read/write buffers and the socket
            socketWriter.close();
            socketReader.close();
            client.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    }

服务器端代码:4 个 Java 文件

    myfileserver.java // First File

    import javax.swing.JOptionPane;
    public class myfileserver {

    /**
     * @param args
     */
    public static void main(String[] args) {

        System.out.println("Server: Start");
        JOptionPane.showMessageDialog(null,"Server Started ","Success",JOptionPane.PLAIN_MESSAGE);
        Multithreading server = new Multithreading(4444);
        server.run();

    }
}

Multithreading.java // Second File

import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Multithreading implements Runnable{

private ServerSocket server;
private ExecutorService pool;

public Multithreading(int listenPort) {

    this.pool = Executors.newFixedThreadPool(50); //Max connections

    try {
        server = new ServerSocket(listenPort);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 public void run() {
     try {

         while(true) {
            pool.execute(new WorkerThread(server.accept()));
         }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}


}

ServerStatistics.java // Third File

public class ServerStatistics {


private static int ConnectionCounter;   //M
private static int FileCounter;         //N

public static synchronized  int getConnectionCounter(){
    return ConnectionCounter;
}

public static synchronized  int getFileCounter(){
    return FileCounter; 
}

public static synchronized  int IncConnectionCounter(){
    return ConnectionCounter++;
}

public static synchronized  int IncFileCounter(){
    return FileCounter++;   
}
}


WorkerThread.java // Fourth File

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JOptionPane;


public class WorkerThread extends Thread {

    public Socket connection;

    public  WorkerThread(Socket connection) {
        this.connection = connection;
        handleConnection();
    }

    private synchronized boolean  handleConnection() {
        try {
            //Increment Connection statistics 
            ServerStatistics.IncConnectionCounter();

            //Create read/write buffers for the socket
            PrintWriter streamWriter = new PrintWriter(connection.getOutputStream());
            BufferedReader  streamReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            //Get filename from client 
            String fileName =  streamReader.readLine();
            System.out.println("server> File " + fileName + " requested from " + connection.getInetAddress().getHostAddress());



            try{
                File myFile = new File (fileName); //Files Are in the Upload directory 

                if(myFile.exists()){
                    //File exists
                    ServerStatistics.IncFileCounter();

                    System.out.println("server> Successful, " + fileName + " exists");
                    System.out.println("server> Total successful requests so far = " + ServerStatistics.getFileCounter() + " out of " + ServerStatistics.getConnectionCounter());

                    //Send N and M
                    streamWriter.println(ServerStatistics.getConnectionCounter() + "," + ServerStatistics.getFileCounter());
                    streamWriter.flush();

                    //Create File buffer to read file to socket
                    byte [] mybytearray  = new byte [(int)myFile.length()];
                    FileInputStream fis = new FileInputStream(myFile);
                    BufferedInputStream bis = new BufferedInputStream(fis);
                    bis.read(mybytearray,0,mybytearray.length);
                    OutputStream os = connection.getOutputStream();

                    //Send File
                    os.write(mybytearray,0,mybytearray.length);
                    os.flush();
                    connection.close();

                    System.out.println("server> File transfer complete [" + fileName + "]");
                    JOptionPane.showMessageDialog(null,"File " + fileName + " requested from " + connection.getInetAddress().getHostAddress() +"\nSuccessful File exists!!" +"\nTotal successful requests so far = " + ServerStatistics.getFileCounter() + " out of " + ServerStatistics.getConnectionCounter() + "\nFile transfer complete [" + fileName + "]" ,"",JOptionPane.PLAIN_MESSAGE);

                }else{
                    //File does not exists
                    System.out.println("server> Not Successful, " + fileName + " does not exists");
                    System.out.println("server> Total successful requests so far = " + ServerStatistics.getFileCounter() + " out of " + ServerStatistics.getConnectionCounter());

                    //Send N and -1 b/c file does not exists
                    streamWriter.println(ServerStatistics.getConnectionCounter() + "," + (-1)); 
                    streamWriter.flush();
                }

                return true;
            }catch (Exception e){//Catch exception if any
                streamWriter.println(ServerStatistics.getConnectionCounter() + ",-1");
                streamWriter.flush();
                System.err.println("Error: " + e.getMessage());
                return false;
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }
}
4

1 回答 1

0

a) 明显变化:

String serverAddress= "127.0.0.1";
    int serverPort=  4444;

String serverAddress= "192.168.1.2";
    int serverPort=  4444;

b) 我将开始检查 192.168.1.2,您可以在服务器运行时执行 netstat -an 并验证它是否正在侦听正确的端口,我还将在服务器中获取数据包捕获以查看 TCP 请求是否来自客户端.

于 2013-04-06T19:11:48.380 回答