Sending binary file over TCP from Python server to Java client - java

I am trying to send binary files over TCP. The server is written in Python and the client in Java.
Server:
import socket;
TCP_IP = '127.0.0.1'
TCP_PORT = 5001;
BUFFER_SIZE = 1024;
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
except:
"Can not bind server on port: "+ str(TCP_PORT) +"\n";
while 1:
print("Wait for connections!!!\n");
conn, addr = s.accept();
print("Receive a new connection!!!\n");
# presentation of client
data = conn.recv(BUFFER_SIZE);
if not data:
conn.close();
print("Lost connection!!!");
continue;
# respond to client
conn.sendall("Hello 1\n");
# receive new request
data = conn.recv(BUFFER_SIZE);
if not data:
continue;
conn.sendall("OK\n");
f = open('testImage.jpg', "rb");
dataRaw = f.read();
f.close();
fileSize = len(dataRaw); #sys.getsizeof(dataRaw);
# send file size
conn.send(str(fileSize) + "\n");
conn.send(dataRaw);
conn.sendall("OK\n");
Client
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class mainTestReceiveFile
{
public static void main(String[] args) throws Exception
{
String usr2ConnectDefault = "127.0.0.1";
int port2ConnectDefault = 5001;
Socket socket;
BufferedReader in;
PrintWriter out;
socket = new Socket(usr2ConnectDefault, port2ConnectDefault);
System.out.println("Connected to server...sending echo string");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
// say hello to server
out.println("Hello");
// read hello from server
String readString = in.readLine();
System.out.println(readString);
out.println("ReadFile");
// verify if request is OK
readString = in.readLine();
if(readString.compareToIgnoreCase("OK") == 0)
System.out.println("Receive new file!!!");
else
{
socket.close();
return;
}
// get size of file
readString = in.readLine();
int sizeOfFile = Integer.parseInt(readString);
//InputStream is = socket.getInputStream();
byte[] fileData = new byte[sizeOfFile];
for(int i = 0; i < sizeOfFile; i++)
{
fileData[i] = (byte)in.read();
}
// save file to disk
FileOutputStream fos = new FileOutputStream("fileImage.jpg");
try
{
fos.write(fileData);
}
finally {
fos.close();
}
// verify if request is OK
readString = in.readLine();
if(readString.compareToIgnoreCase("OK") == 0)
System.out.println("New file received!!!");
else
{
socket.close();
return;
}
socket.close();
}
}
I am trying to send for example one image. In the client side, the image received has the same size (file size and number of pixels) but the data is corrupted.

Related

Java - Missing first letter in every lines

I'm creating File Transfer program that will transfer a file to client. But when I transferred the file, It missing the first letter of every lines. What's wrong with my code?
I'm pretty new at java so I don't know what to do next. I've tried changing byte size but no help. What should I do?
Server.java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
class Server {
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket serverSocket = null;
Scanner scan = new Scanner(System.in);
String fileSend;
System.out.print("Type the path to the file to send >> ");
fileSend = scan.nextLine();
try {
serverSocket = new ServerSocket(5467);
} catch (Exception e) {
System.out.println("Could not bind to port 5467, Maybe address is already is use or you need to run as administrator");
return;
}
System.out.println("Listening on port 5467");
System.out.println("Waiting for the connection...");
while (true) {
File FileSend = null;
Socket socket = serverSocket.accept();
OutputStream out = socket.getOutputStream();
System.out.println("Accepted connection : " + socket);
InputStream in = socket.getInputStream();
DataInputStream dataIn = new DataInputStream(in);
String login = dataIn.readUTF();
String password = dataIn.readUTF();
String result = "You credential is ";
if (login.equals("1c18b5cdef8f9b4c5d6b2ad087265e597d1d4639337b73a04a335103c00ec64b") && password.equals("1c18b5cdef8f9b4c5d6b2ad087265e597d1d4639337b73a04a335103c00ec64b13d0b73358bfa8978dfaaf180565bcfecd3dc0631cda525920865145fb3fa131")) {
result += "correct";
} else {
result += "incorrect";
}
DataOutputStream dataOut = new DataOutputStream(out);
try {
dataOut.writeUTF(result);
} catch (FileNotFoundException e) {
System.out.println("No such file or directory");
}
finally
{
FileSend = new File(fileSend);
byte[] FileByteArray = new byte[(int) FileSend.length()];
try {
fis = new FileInputStream(FileSend);
}
catch (FileNotFoundException e) {
System.out.println("No such file or directory");
return;
}
bis = new BufferedInputStream(fis);
File myFile = new File (fileSend);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = socket.getOutputStream();
System.out.println("Sending " + fileSend + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
}
}
}
}
Client.java
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Client {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
Socket socket = null;
String PlainLogin;
String FileOut;
String PlainPassword;
Scanner scan = new Scanner(System.in);
System.out.print("What is the IP address of the server >> ");
String host = scan.nextLine();
try {
socket = new Socket(host, 5467);
} catch (ConnectException | NullPointerException e) {
System.out.println("Connection Refused, Have you run the server first?");
return;
}
OutputStream out = socket.getOutputStream();
DataOutputStream dataOut = new DataOutputStream(out);
InputStream is = socket.getInputStream();
System.out.println("Connection Established");
System.out.println("Credential Required, Please login");
System.out.print("Type your username >> ");
PlainLogin = scan.next();
System.out.print("Type your password >> ");
PlainPassword = scan.next();
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hashInBytes = md.digest(PlainLogin.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hashInBytes) {
sb.append(String.format("%02x", b));
}
String HashedLogin = sb.toString();
byte[] hashInBytesP = md.digest(PlainPassword.getBytes(StandardCharsets.UTF_8));
for (byte b : hashInBytesP) {
sb.append(String.format("%02x", b));
}
String HashedPassword = sb.toString();
dataOut.writeUTF(HashedLogin);
dataOut.writeUTF(HashedPassword);
InputStream in = socket.getInputStream();
DataInputStream dataIn = new DataInputStream(in);
String str = dataIn.readUTF();
if (str == "Your credential is incorrect") {
System.out.println(str);
return;
} else {
System.out.print("Type any file name you want >> ");
scan.nextLine();
FileOut = scan.nextLine();
OutputStream output = new FileOutputStream(FileOut);
byte[] mybytearray = new byte[1024];
is.read(mybytearray, 0, mybytearray.length);
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
output.write(buffer, 0, bytesRead);
}
output.close();
socket.close();
dataIn.close();
System.out.println("Done");
return;
}
}
}
I expect it to show full text like "Java", but it only show "ava"
File is Serializable, so I would suggest you should simply try to send it directly via ObjectOutputStream / ObjectInputStream.
For example on Server side :
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
...
out.writeObject(yourFileObject);
And on Client :
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
...
File receivedFile = null;
try {
receivedFile = (File) in.readObject();
}
catch (IOException e) {
...
}
I'm not entirely sure why this happens exactly, but you shouldn't be using DataInputStream which "lets an application read primitive Java data types", but an InputStreamReader which "is a bridge from byte streams to character streams".
Also, you can wrap that reader into a BufferedReader which lets you read line by line, and you'll end up with something like
try (BufferedReader reader=new BufferedReader(new InputStreamReader(inStream, UTF8));
PrintWriter writer = new PrintWriter(file)) {
reader.lines().forEach(writer::println);
}
for an upload, or
try (PrintWriter writer = new PrintWriter(outStream)) {
Files.lines().forEach(writer::println);
}
for download.

Java UDP - server accepting packets on multiple ports

I have quite a complex question here, I hope understanding my code won't be such a problem.
I'm writing a program based on UDP and TCP communication in Java.
Server is listening on several UDP ports (1. number and quantity of ports is given by a user in program parameters; 2. A Thread is created for each port) for a packets from Clients (there can be more than one trying to send a packet at a time to Server). Each packet contains Clients id, the message and UDP port number of the Client who send this packet. Server receives the packet, puts the message in a HashMap (Client id is the key, sent messages are stored in a List of Strings). On each packet received, Servers checks the List of Strings whether the messages sent from specified Client are matching a password. If the messages are in correct order, Server sends a generated port number for TCP communication with the Client who has sent the correct password, opens ServerSockets, they perform a simple communication and the Client closes.
Now, a Client should be able to send his messages to various ports. For example, Server is listening on ports 2000 and 3000. A Client should be able to send 2 messages to port 2000 and another two messages on port 3000. However, the Server seems to be be receiving messages only on the first opened port.
If a Client sends all his messages on one port, it all works fine.
Here is the Server class:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
public class Server {
static int portsOpenedQuantity;
static HashMap<String, List<String>> packetsReceived = new HashMap<>();
static List<Integer> portsTCP = new ArrayList<>();
public static void main(String[] args) {
portsOpenedQuantity = args.length;
List<String> listOfPorts = new ArrayList<>();
for(int i = 0; i < portsOpenedQuantity; ++i)
if(!listOfPorts.contains(args[i]) && (Integer.parseInt(args[i]) > 1024))
listOfPorts.add(args[i]);
for(int i = 0; i < listOfPorts.size(); ++i) {
final int j = i;
System.out.println("SERVER listening on port: " + listOfPorts.get(j));
Thread listeningPort = new Thread(new Runnable() {
#Override
public void run() {
synchronized (packetsReceived){
try {
byte[] packetReceived = new byte[256];
DatagramSocket ds = new DatagramSocket(Integer.parseInt(listOfPorts.get(j)));
DatagramPacket dp = new DatagramPacket(packetReceived, 256);
while(true){
ds.receive(dp);
List<String> sequence = new ArrayList<>();
System.out.println("SERVER received a packet");
String msgReceived = new String(dp.getData(), 0, dp.getLength());
String[] separatedMsg = msgReceived.split(" ");
int portUDPNumber = Integer.parseInt(separatedMsg[2]);
System.out.println("Id: " + separatedMsg[0]);
System.out.println("Value: " + separatedMsg[1]);
System.out.println("Port UDP: " + separatedMsg[2]);
if(packetsReceived.containsKey(separatedMsg[0])) {
sequence = packetsReceived.get(separatedMsg[0]);
packetsReceived.remove(separatedMsg[0]);
System.out.println(separatedMsg[1]);
sequence.add(separatedMsg[1]);
System.out.println(sequence);
packetsReceived.put(separatedMsg[0], sequence);
} else {
System.out.println(sequence);
sequence.add(separatedMsg[1]);
packetsReceived.put(separatedMsg[0], sequence);
}
String sequenceResult = "";
for(int k = 0; k < sequence.size(); ++k) {
sequenceResult += sequence.get(k);
}
System.out.println(sequenceResult);
if(sequenceResult.equals("!##$")){
System.out.println("Connecting via TCP...");
int portNumber = (int)((Math.random()*100)+5000);
boolean portAvailable = true;
ServerSocket ss = null;
System.out.println("TCP port number: " + portNumber);
while(portAvailable) {
try{
ss = new ServerSocket(portNumber);
portsTCP.add(portNumber);
portAvailable = false;
} catch(Exception e) {
portAvailable = true;
portNumber++;
}
}
System.out.println("socket number aquired");
String portNr = portNumber+"";
byte[] portNrToSend = portNr.getBytes();
dp = new DatagramPacket(portNrToSend, portNrToSend.length, InetAddress.getByName("localhost"), portUDPNumber);
System.out.println("Datagram created");
ds.send(dp);
System.out.println("Datagram sent");
Socket s = ss.accept();
System.out.println("Port number sent to: " + portUDPNumber);
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String msgFromClient = in.readLine();
System.out.println("Message from client: " + msgFromClient);
out.println("I received your message");
in.close();
out.close();
s.close();
ss.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
listeningPort.start();
}
}
}
And the Client class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
public class Client {
InetAddress ip;
String idClient;
List<Integer> portsUDP = new ArrayList<>();
String sequence;
public Client(String[] args) {
try {
ip = InetAddress.getByName(args[0]);
idClient = args[1];
for(int i = 2; i < args.length; ++i)
portsUDP.add(Integer.parseInt(args[i]));
this.sequence = "!##$";
DatagramSocket ds = new DatagramSocket();
DatagramPacket dp = null;
for(int i = 0; i < portsUDP.size(); ++i) {
byte[] toSend = new byte[256];
String msgToSend = idClient + " " + sequence.charAt(i) + " " + ds.getLocalPort();
System.out.println("CLIENT named as: " + idClient + " sends a message: " + sequence.charAt(i) + " " + ds.getLocalPort());
toSend = msgToSend.getBytes();
dp = new DatagramPacket(toSend, toSend.length, ip, portsUDP.get(i));
ds.send(dp);
System.out.println("CLIENT: " + idClient + " sent a packet");
toSend = new byte[256];
msgToSend = "";
}
String received;
byte[] tabReceived = new byte[256];
dp = new DatagramPacket(tabReceived, tabReceived.length);
System.out.println("Datagram created");
ds.receive(dp);
System.out.println("Datagram received");
received = new String(dp.getData(), 0, dp.getLength());
System.out.println("Received TCP port number: " + received);
int portTCP = Integer.parseInt(received);
int portNumber = (int)((Math.random()*100)+5000);
boolean portAvailable = true;
ServerSocket ss = null;
while(portAvailable) {
try{
ss = new ServerSocket(portNumber);
portAvailable = false;
} catch(Exception e) {
portAvailable = true;
portNumber++;
}
}
System.out.println("ServerSocket created");
Socket s = new Socket(ip, portTCP);
System.out.println("Socket created");
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out.println("Succes of communication");
String msgFromServer = in.readLine();
System.out.println("Message from SERVER: " + msgFromServer);
in.close();
out.close();
s.close();
ss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Client(args);
}
}
I think what is creating problems here is the synchronization on the HashMap, but when I run it without synchronization, the packets come in a completely random sequence, are not stored in the HashMap properly - it's just much worse.
I'd be grateful for any suggestions and comments.
Your Runnable loops forever after obtaining a lock on a shared object called packetsReceived, so only one of your Threads will actually be able to accomplish anything; the other thread will wait for the lock forever.
You should be able to verify this with a simple thread dump while your sample program is running.
The solution (to the synchronization problem) is to only obtain that lock when you want to actually modify the HashMap. So, remove the synchronized(packetsReceived) from outside the loop and put it around the code that actually performs the containsKey/remove/put calls on the HashMap.

Datagram Packet FTP application

I write a FTP application using UDP Datagram Protocol , and I need the client side read from file 100 character and send it in 5 parts , 20 characters in each part , when I run my program I get this error :
Exception in thread "main" java.lang.IllegalArgumentException: illegal length or offset. I want the server get each line in five parts but sort it accordingly.
this is my code :
import java.net.*;
import java.io.*;
public class FTPClient
{
public static void main(String[] args)
{
final int SIZE=100;
DatagramSocket skt= null;
DatagramPacket pkt = null;
BufferedReader read= null;
int port = 3131;
try
{
skt=new DatagramSocket(2121);
read= new BufferedReader(new FileReader("input.txt"));
String line = read.readLine();
byte[] lineByte = new byte[SIZE];
lineByte = line.getBytes();
InetAddress add = InetAddress.getByName("localhost");
for(int i=0;i<100;i+=20)
{
pkt = new DatagramPacket(lineByte,i,20,add,port);
skt.send(pkt);
}
}
catch(IOException e)
{
System.out.println(e.getMessage()); }
finally
{
skt.close();
// read.close();
}
}
}
Your code with comments at problem areas. If you still have problems resolving the issues after reading my comments, just add a comment and I will explain more
public static void main(String[] args) {
final int SIZE = 100;
DatagramSocket skt = null;
DatagramPacket pkt = null;
BufferedReader read = null;
int port = 3131;
try {
skt = new DatagramSocket(2121);
read = new BufferedReader(new FileReader("input.txt"));
String line = read.readLine(); // how long is the line?
byte[] lineByte = new byte[SIZE]; // this is a redundant assignment
lineByte = line.getBytes(); // now the length of the lineBytes is "unknown"
InetAddress add = InetAddress.getByName("localhost");
for (int i = 0; i < 100; i += 20) { // you should check the length of lineBytes instead of 100
pkt = new DatagramPacket(lineByte, i, 20, add, port);
skt.send(pkt);
}
}
catch (IOException e) {
System.out.println(e.getMessage());
}
finally {
skt.close();
// read.close();
}
}

Multicast a file to a group of users

I have a problem to send a file to a group of users. Users could receive the file was sent from server but the file would not be saved if it is less than 8kb.
Here is the code:
MulticastSocketServer
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class MulticastSocketServer{
public static void main(String[] args) {
String fileName;
String address = "235.0.0.1";
int port = 2222;
Scanner in = new Scanner(System.in);
System.out.print("Please enter file name : ");
fileName = in.next();
try (DatagramSocket serverSocket = new DatagramSocket()) {
InetAddress addr = InetAddress.getByName(address);
BufferedReader br = new BufferedReader(new FileReader(fileName + ".txt"));
DatagramPacket fn = new DatagramPacket(fileName.getBytes(),fileName.getBytes().length, addr, port);
serverSocket.send(fn);
DatagramPacket msgPacket = null;
String txt = "";
while((txt = br.readLine())!=null){
msgPacket = new DatagramPacket(txt.getBytes(),txt.getBytes().length, addr, port);
serverSocket.send(msgPacket);
System.out.println(txt);
}
}catch (IOException ex) {ex.printStackTrace();}
}
}
MulticastSocketClient
import java.io.*;
import java.net.*;
public class MulticastSocketClient {
public static void main(String[] args) throws UnknownHostException {
int port = 2222;
String address = "235.0.0.1";
InetAddress addr = InetAddress.getByName(address);
byte[] buf = new byte[64];
byte[] buf2 = null ;
try (MulticastSocket clientSocket = new MulticastSocket(port)){
clientSocket.joinGroup(addr);
DatagramPacket fn = new DatagramPacket(buf, buf.length);
clientSocket.receive(fn);
String name = new String(buf, 0, buf.length);
String fileName = name.trim();
try(PrintWriter pw = new PrintWriter(new FileWriter(fileName+"2.txt"))){
while (true) {
buf2 = new byte [1024];
DatagramPacket msgPacket = new DatagramPacket(buf2, buf2.length);
clientSocket.receive(msgPacket);
String msg = new String(buf2,0,buf2.length);
String txt = msg.trim();
pw.println(txt);
System.out.println(txt);
}
}catch(FileNotFoundException ex){ex.printStackTrace();}
} catch (IOException ex) {ex.printStackTrace();}
}
}
You're never exiting the while (true) loop, because you don't have any mechanism for transmitting end of stream, so you're never closing the PrintWriter, so it isn't flushing its final buffer, so any file < 4096 chars won't get flushed at all, so it will be zero length.
However your code has much worse problems that this. You are assuming:
the filename fits into 1024 characters
every line of the input file fits into 1024 bytes
the filename is received first
all the content packets are received
all the content packets are received in order
all the content packets are received exactly once
the length of every datagram is 1024
the data is text, not binary, and can be converted losslessly to a String
You're using UDP. That means that most of these assumptions are invalid.

Filtering URL content in a self written proxy using Java

I need to code some proxy server for an assignment in my university. It should be able to display the content of some simple web page given by our professor.
Additionally it should filter the URL and the URL content, and block the web page if one of these contain one of the words in my "bad" array.
My question is, how can I perform this filtering in Java.
Code:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ProxyServer{
//Crate the Port the user wants the proxy to be on
static Scanner sc = new Scanner(System.in);
public static final int portNumber = sc.nextInt();
public static void main(String[] args) {
ProxyServer proxyServer = new ProxyServer();
proxyServer.start();
}
public void start() {
System.out.println("Starting the SimpleProxyServer ...");
try {
String bad[]= new String[4];
bad[0]= "Spongebob";
bad[1]= "Britney Spears";
bad[2]= "Norrköping";
bad[3]= "Paris Hilton";
ServerSocket serverSocket = new ServerSocket(ProxyServer.portNumber);
System.out.println(serverSocket);
byte[] buffer= new byte [1000000] ;
while (true) {
Socket clientSocket = serverSocket.accept();
InputStream inputstream = clientSocket.getInputStream();
System.out.println(" DAS PASSIERT VOR DEM BROWSER REQUEST:");
int n = inputstream.read(buffer);
String browserRequest = new String(buffer,0,n);
System.out.println("Das ist der Browserrequest: "+browserRequest);
System.out.println("Das ist der Erste Abschnitt");
int start = browserRequest.indexOf("Host: ") + 6;
int end = browserRequest.indexOf('\n', start);
String host = browserRequest.substring(start, end - 1);
System.out.println("Connecting to host " + host);
Socket hostSocket = new Socket(host, 80); //I can change the host over here
OutputStream HostOutputStream = hostSocket.getOutputStream();
PrintWriter writer= new PrintWriter (HostOutputStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream));
String Input= null;
while (((Input= reader.readLine())!= null)){
writer.write(Input);
writer.flush();
System.out.println("Empfangen vom Client: "+Input);
}
// for (int i=0; i<4;i++){
// if (inString.contains(bad[i])){
// System.out.println("Bye Idiot");
// break;
// }
// }
System.out.println("Forwarding request to server");
HostOutputStream.write(buffer, 0, n);// but then the buffer that is fetched from the client remains same
HostOutputStream.flush();
InputStream HostInputstream = hostSocket.getInputStream();
OutputStream ClientGetOutput = clientSocket.getOutputStream();
System.out.println("Forwarding request from server");
do {
n = HostInputstream.read(buffer);
String inhalt= HostInputstream.toString();
System.out.println("das ist der inhalt vom HOST: "+ inhalt);
String vomHost = new String(buffer,0,n);
System.out.println("Vom Host\n\n"+vomHost);
// for(int i=0;i<n;i++){
// System.out.print(buffer[i]);
// }
System.out.println("Receiving " + n + " bytes");
if (n > 0) {
ClientGetOutput.write(buffer, 0, n);
}
} while (HostInputstream.read(buffer)!= -1);//n>0
ClientGetOutput.flush();
hostSocket.close();
clientSocket.close();
System.out.println("End of communication");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Categories

Resources