Socket and TCP in java

Possible duplicate:
how to implement a TCP server and a TCP client in java to transfer files

I am writing an application that will send files to a server through a socket. Its very important correct version for all files from client to server without errors, lost data, etc. For this I need to use the TCP protocol, I think, but I do not know how to do this. A socket in Java uses TCP by default. If not, how can I send data over TCP? Thanks for any help and hint.

+4
source share
3 answers

And here is a good example from this Java TCP socket stream : data transfer is slow

import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class Transfer { public static void main(String[] args) { final String largeFile = "/home/dr/test.dat"; // REPLACE final int BUFFER_SIZE = 65536; new Thread(new Runnable() { public void run() { try { ServerSocket serverSocket = new ServerSocket(12345); Socket clientSocket = serverSocket.accept(); long startTime = System.currentTimeMillis(); byte[] buffer = new byte[BUFFER_SIZE]; int read; int totalRead = 0; InputStream clientInputStream = clientSocket.getInputStream(); while ((read = clientInputStream.read(buffer)) != -1) { totalRead += read; } long endTime = System.currentTimeMillis(); System.out.println(totalRead + " bytes read in " + (endTime - startTime) + " ms."); } catch (IOException e) { } } }).start(); new Thread(new Runnable() { public void run() { try { Thread.sleep(1000); Socket socket = new Socket("localhost", 12345); FileInputStream fileInputStream = new FileInputStream(largeFile); OutputStream socketOutputStream = socket.getOutputStream(); long startTime = System.currentTimeMillis(); byte[] buffer = new byte[BUFFER_SIZE]; int read; int readTotal = 0; while ((read = fileInputStream.read(buffer)) != -1) { socketOutputStream.write(buffer, 0, read); readTotal += read; } socketOutputStream.close(); fileInputStream.close(); socket.close(); long endTime = System.currentTimeMillis(); System.out.println(readTotal + " bytes written in " + (endTime - startTime) + " ms."); } catch (Exception e) { } } }).start(); } } 
+6
source

Yes, you can use TCP for this and yes, Java sockets can run TCP.

If I were you, I would start with this guide: http://download.oracle.com/javase/tutorial/networking/sockets/

+9
source

Yes, Java can read and write a file over TCP.

http://download.oracle.com/javase/tutorial/networking/sockets/ is a good place to start learning Java Sockets.

You will also need to read the documentation for these two packages.

java.io

java.net

+2
source

All Articles