Jump to content

Recommended Posts

Posted

As part of a schematic system i am currently working on i am trying to make it possible to send schematic files from a client to the server. These files are potentially much to large to send via the default packet system so i am trying to create my own file transfer system.

 

I didn't know anything about sending files so i did some research and came up with the following system.

 

It works fine when sending to a server running on my local machine but when i try to actually send a file to a server over the net it throws

"ConnectException: Connection timed out: connect" on the server side.

 

I dont know a lot about sending files and its rather hard to debug code running on a server half way around the world so im hoping someone can help me out with this.

 

FileSender (client side code)

 

@SideOnly(Side.CLIENT)
public class FileSender
{
public static final FileSender instance = new FileSender();
private SenderThread thread;
private String file = null;
private int port;

public FileSender()
{
}


public void sendFile(String file, int port)
{
	if (this.thread != null && this.thread.getRunning()) {
		Minecraft.getMinecraft().thePlayer.addChatComponentMessage(new ChatComponentText(EnumChatFormatting.RED + "File transfer already in progress"));
		return;
	}
	this.thread = new SenderThread(this);
	this.file = file;
	this.thread.setRunning(true);
	this.thread.start();
	this.port = port;
}


public class SenderThread extends Thread
{
	private FileSender sender;
	private boolean running = false;

	public SenderThread(FileSender sender)
	{
		super("TT File Sender Thread");
		this.sender = sender;
	}

	@Override
	public void run()
	{
		if (sender.file == null) return;
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		OutputStream os = null;
		ServerSocket servsock = null;
		Socket sock = null;

		LogHelper.info("Waiting for connection... [" + port + "]");
		try
		{
			servsock = new ServerSocket(port);
			sock = servsock.accept();
			LogHelper.info("Accepted connection : " + sock);

			File myFile = SchematicHandler.getFile(sender.file);
			byte [] mybytearray  = new byte [(int)myFile.length()];
			fis = new FileInputStream(myFile);
			bis = new BufferedInputStream(fis);
			os = sock.getOutputStream();

			LogHelper.info("Sending " + myFile.getName() + "(" + mybytearray.length + " bytes)");

			int count;
			while ((count = bis.read(mybytearray)) > 0)
			{
				os.write(mybytearray, 0, count);
			}

			os.flush();
			LogHelper.info("Done.");

			running = false;
			sender.file = null;
		}
		catch (IOException e)
		{
			running = false;
			sender.file = null;
			e.printStackTrace();
		}

	}

	public boolean getRunning() { return running; }

	public void setRunning(boolean b) { this.running = b; }
}
}

 

 

FileReceiver (server side code)

 

@SideOnly(Side.SERVER)
public class FileReceiver
{
public static FileReceiver instance = new FileReceiver();
private ReceiverThread thread;
private EntityPlayer client;
private InetAddress clientAddress;
private String fileName;


public void receiveFile(String fileName, NetHandlerPlayServer netHandler)
{
	if (this.thread != null && this.thread.getTransferInProgress()){
		netHandler.playerEntity.addChatComponentMessage(new ChatComponentText(EnumChatFormatting.RED + "A file transfer is already in progress from another client"));
		return;
	}
	this.client = netHandler.playerEntity;
	this.clientAddress = ((InetSocketAddress)netHandler.func_147362_b().channel().remoteAddress()).getAddress();
	LogHelper.info("Receiving file from: " + this.clientAddress);
	client.addChatComponentMessage(new ChatComponentText("Receiving file from: " + this.clientAddress));
	this.fileName = fileName;
	this.thread = new ReceiverThread(this);
	this.thread.transferInProgress = true;
	this.thread.start();
}

public boolean getTransferInProgress() { return thread != null && thread.getTransferInProgress(); }


public class ReceiverThread extends Thread
{
	private FileReceiver receiver;
	private boolean transferInProgress;

	public ReceiverThread(FileReceiver receiver)
	{
		super("TT File Receiver Thread");
		this.receiver = receiver;
	}

	@Override
	public void run()
	{
		try
		{
			Socket socket;
			InputStream is;
			FileOutputStream fos;
			BufferedOutputStream bos;

			client.addChatComponentMessage(new ChatComponentText("Attempting to connect"));
			LogHelper.info("Attempting to connect");

                                // ######## This is where it throws the exception ########
			socket = new Socket(receiver.clientAddress, ConfigHandler.filePort /*port being used is 25566 also tried 25565*/);  

			LogHelper.info("Connection established");
			client.addChatComponentMessage(new ChatComponentText("Connection established"));

			is = socket.getInputStream();
			fos = new FileOutputStream(new File(SchematicHandler.getSaveFolder(), receiver.fileName + ".schematic"));
			bos = new BufferedOutputStream(fos);

			int size = socket.getReceiveBufferSize();

			byte [] bytes  = new byte [size];

			receiver.client.addChatComponentMessage(new ChatComponentText(EnumChatFormatting.GREEN + "Upload in progress..."));

			int count;
			while ((count = is.read(bytes)) > 0) {
				bos.write(bytes, 0, count);
			}

			bos.flush();

			is.close();
			fos.close();
			bos.close();
			socket.close();

			LogHelper.info("File " + receiver.fileName + " downloaded [" + size + "]");
			receiver.client.addChatComponentMessage(new ChatComponentText(EnumChatFormatting.GREEN + "Upload Complete"));
		}
		catch (IOException e)
		{
			client.addChatComponentMessage(new ChatComponentText(EnumChatFormatting.RED + "Upload Failed [iOException]"));
			e.printStackTrace();
		}

		transferInProgress = false;
	}


	public boolean getTransferInProgress() { return transferInProgress; }
}

}

 

 

The packet that handles the operation

 

public static class Handler implements IMessageHandler<PacketFileTransfer, IMessage>
{
@Override
public IMessage onMessage(PacketFileTransfer message, MessageContext ctx)
{
	if (ctx.side == Side.CLIENT)
	{
		if (SchematicHandler.loadCompoundFromFile(message.fileName) != null) {
			TownBuilder.proxy.sendFile(message.fileName, message.port);
			return new PacketFileTransfer(message.fileName, true);
		}
		else return new PacketFileTransfer(message.fileName, false);
	}
	else
	{
		if (message.transferValid)
		{
			TownBuilder.proxy.receiveFile(message.fileName, ctx.getServerHandler());
		}
		else ctx.getServerHandler().playerEntity.addChatComponentMessage(new ChatComponentText("That file dose not exist on your client"));
	}
	return null;
}
}

 

 

Server proxy

 

public void sendFile(String file, int port){}

public void receiveFile(String fileName, NetHandlerPlayServer netHandler)
{
FileReceiver.instance.receiveFile(fileName, netHandler);
}

public boolean isTransferInProgress() { return FileReceiver.instance.getTransferInProgress(); }

 

 

Client proxy

 

@Override
public void sendFile(String file, int port) {
FileSender.instance.sendFile(file, port);
}

@Override
public void receiveFile(String fileName, NetHandlerPlayServer netHandler) {}

@Override
public boolean isTransferInProgress() {
return false;
}

 

 

I am the author of Draconic Evolution

Posted

After a bit more troubleshooting i believe the connection is being blocked by the firewall on ether my router or my pc. If that is the case how can i get around that? (how dose minecrafts connection work?)

 

Or better yet would there be a way i could use minecrafts existing connection to send the file?

 

Any help with this would be greatly appreciated. 

I am the author of Draconic Evolution

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.