我是java的初学者,也是socket编程的初学者。
我编写的这个程序旨在允许客户端和服务器之间的p2p文件同步。
当对等方与另一个对等方建立TCP连接时,它们都将比较它们拥有的文件列表并继续交换文件,以便它们都具有 相同的文件。 TCP连接必须保持打开状态,直到在连接的任一端手动终止对等进程。
我查看了在线教程和类似的程序来编写这个程序的代码。但是,运行服务器后,运行客户端时控制台上会显示以下错误。
IOException: java.net.ConnectException: Connection timed out: connect
请告诉我如何解决错误。非常感谢提前!
这是我的代码供参考。
服务器:
package bdn;
import java.net.*;
import java.io.*;
import java.util.*;
public class MultipleSocketServer extends Thread{
// private Socket connection;
private String TimeStamp;
private int ID;
static int port = 6789;
static ArrayList<File> currentfiles = new ArrayList<File>();
static ArrayList<File> missingsourcefiles = new ArrayList<File>();
public static void main(String[] args)
{
File allFiles = new File("src/bdn/files");
if (!allFiles.exists()) {
if (allFiles.mkdir()) {
System.out.println("Directory is created.");
}
}
//Load the list of files in the directory
listOfFiles(allFiles);
try {
new MultipleSocketServer().startServer();
} catch (Exception e) {
System.out.println("I/O failure: " + e.getMessage());
e.printStackTrace();
}
}
public static void listOfFiles(final File folder){
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listOfFiles(fileEntry);
} else {
//System.out.println(fileEntry.getName());
currentfiles.add(fileEntry.getAbsoluteFile());
}
}
}
public void startServer() throws Exception {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + port);
System.exit(-1);
}
while (listening) {
handleClientRequest(serverSocket);
}
//serverSocket.close();
}
private void handleClientRequest(ServerSocket serverSocket) {
try {
new ConnectionRequestHandler(serverSocket.accept()).run();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Handles client connection requests.
*/
public class ConnectionRequestHandler implements Runnable{
private Socket _socket = null;
public ConnectionRequestHandler(Socket socket) {
_socket = socket;
}
public void run() {
System.out.println("Client connected to socket: " + _socket.toString());
try {
ObjectOutputStream oos = new ObjectOutputStream (_socket.getOutputStream());
oos.flush();
oos.writeObject(currentfiles); //sending to client side.
oos.flush();
} catch (IOException e) {
e.printStackTrace();
}
syncMissingFiles();
}
@SuppressWarnings("unchecked")
public void syncMissingFiles(){
try {
ObjectInputStream ois = new ObjectInputStream(_socket.getInputStream());
System.out.println("Is the socket connected="+_socket.isConnected());
missingsourcefiles= (ArrayList<File>) ois.readObject();
System.out.println(missingsourcefiles);
//add missing files to current file list.
ListIterator<File> iter = missingsourcefiles.listIterator();
File temp_file;
while (iter.hasNext()) {
// System.out.println(iter.next());
temp_file = iter.next();
currentfiles.add(temp_file);
}
} catch (IOException e) {
e.printStackTrace();
} catch ( ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
客户端:
package bdn;
import java.net.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.ListIterator;
/* The java.io package contains the basics needed for IO operations. */
import java.io.*;
public class SocketClient {
/** Define a port */
static int port = 2000;
static Socket peer_socket = null;
static String peerAddress;
static ArrayList<File> currentfiles = new ArrayList<File>();
static ArrayList<File> sourcefiles = new ArrayList<File>();
static ArrayList<File> missingsourcefiles = new ArrayList<File>();
static ArrayList<File> missingcurrentfiles = new ArrayList<File>();
SocketClient(){}
public static void listOfFiles(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listOfFiles(fileEntry);
} else {
//System.out.println(fileEntry.getName());
currentfiles.add(fileEntry.getAbsoluteFile());
}
}
}
@SuppressWarnings("unchecked")
public static void getListfromPeer() {
try {
ObjectInputStream inList =new ObjectInputStream(peer_socket.getInputStream());
sourcefiles = (ArrayList<File>) inList.readObject();
} catch (ClassNotFoundException e) {
System.err.println("Error in data type.");
}catch (IOException classNot){
System.err.println("Error in data type.");
}
}
public static void compareList1() {
//Compare the source files and current files. If not in current files, add the files to "missingcurrentfiles".
ListIterator<File> iter = sourcefiles.listIterator();
File temp_file;
while (iter.hasNext()) {
// System.out.println(iter.next());
temp_file = iter.next();
if (!currentfiles.contains(temp_file)) //file cannot be found
{
missingcurrentfiles.add(temp_file);
}
}
}
public static void compareList2() {
//Compare the source files and current files. If not in current files, add the files to "missingsourcefiles".
ListIterator<File> iter = currentfiles.listIterator();
File temp_file;
while (iter.hasNext()) {
// System.out.println(iter.next());
temp_file = iter.next();
if (!sourcefiles.contains(temp_file)) //file cannot be found
{
missingsourcefiles.add(temp_file);
}
}
}
public static void main(String[] args) {
//Make file lists of the directory in here.
File allFiles = new File("src/bdn/files");
if (!allFiles.exists()) {
if (allFiles.mkdir()) {
System.out.println("Directory is created.");
}
}
/*Get the list of files in that directory and store the names in array*/
listOfFiles(allFiles);
/*Connect to peer*/
try {
new SocketClient().transfer();
//new TcpClient().checkForInput();
} catch (Exception e) {
System.out.println("Failed at main" + e.getMessage());
e.printStackTrace();
}
}
public void transfer(){
getPeerAddress();
// StringBuffer instr = new StringBuffer();
// String TimeStamp;
try {
/** Obtain an address object of the server */
// InetAddress address = InetAddress.getByName(host);
// System.out.println("Address of connected host:"+ address);
/** Establish a socket connection */
Socket connection = new Socket(peerAddress, port);
System.out.println("New SocketClient initialized");
getListfromPeer();
compareList1();
compareList2();
System.out.println(missingcurrentfiles);
System.out.println(missingsourcefiles);
/** Instantiate a BufferedOutputStream object */
// BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
/** Instantiate an ObjectOutputStream*/
ObjectOutputStream oos = new ObjectOutputStream(connection.getOutputStream());
oos.flush();
/*
TimeStamp = new java.util.Date().toString();
String process = "Calling the Socket Server on "+ host + " port " + port +
" at " + TimeStamp + (char) 13;
*//** Write across the socket connection and flush the buffer *//*
oos.writeObject(process);
oos.flush();*/
oos.writeObject(missingsourcefiles);
oos.flush();
System.out.println("Missing files in source sent back.");
}
catch (IOException f) {
System.out.println("IOException: " + f);
}
catch (Exception g) {
System.out.println("Exception: " + g);
}
}
public void syncMissingFiles(){
//add missing files to current file list.
ListIterator<File> iter = missingcurrentfiles.listIterator();
File temp_file;
while (iter.hasNext()) {
// System.out.println(iter.next());
temp_file = iter.next();
currentfiles.add(temp_file);
}
}
public static void getPeerAddress() {
// prompt the user to enter the client's address
System.out.print("Please enter the IP address of the client :");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// read the IP address from the command-line
try {
peerAddress = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read client's IP address!");
System.exit(1);
}
System.out.println("Thanks for the client's IP address, " + peerAddress);
}
}
答案 0 :(得分:0)
从我注意到的,我不是专家,您将服务器设置为在客户端连接到端口2000时侦听端口6789。 它们应该在同一个端口上工作。
尝试在客户端构造函数中执行以下操作。
SocketClient(String servername){
//while port is same as server port
peer_socket = new Socket(servername, port);
}
如果您在本地工作,可以将主服务器中的服务器名称设置为“localhost”
此外,我建议您验证您正在使用的端口是否未被计算机上现有的任何防火墙阻止。