These classes succeed to communicate when they are on the same computer. But as soon as we move the "Antenna" to another computer(still on same network) the server still gets the package BUT the client just keeps waiting for a reply.
We have checked som other threads at this site but we still can't find our problem. Anyone who can help?
SERVER RECEIVER CLASS:
package Server;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.util.Vector;
public class RecieverProxy extends Thread {
private DatagramSocket socket;
private static int length;
private String reqS;
public static java.util.Date date = new java.util.Date();
public static Timestamp currentTimestamp = new Timestamp(date.getTime());
#Override
public void run() {
try {
System.out.println(currentTimestamp + " Server[IP=\""
+ InetAddress.getLocalHost().getHostAddress()
+ "\"]: Local server is Running...");
System.out.println(currentTimestamp
+ " SERVER: Connecting to MySQL server...");
DbUpdater.readyDatabase();
System.out.println(currentTimestamp
+ " SERVER: MySQL server is connected!");
} catch (UnknownHostException e) {
e.printStackTrace();
System.exit(1);
}
System.err.println(currentTimestamp + " SERVER: Ready... waiting...");
try {
recieveSendUDP();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* The method will wait for a request, process the request, and then return
* the reply.
*
* #throws InterruptedException
*/
public boolean recieveSendUDP() throws IOException, InterruptedException {
socket = new DatagramSocket(6789);
// modtag forespørgsler
while (true) {
try {
byte[] bytes = new byte[1000];
DatagramPacket request = new DatagramPacket(bytes, bytes.length);
socket.receive(request);
length = request.getLength();
String replyS = "ERROR";
String oldreqS = new String(request.getData());
if (oldreqS == "[]") {
System.out.println(currentTimestamp
+ " None bluetooth devices nearby");
replyS = "None bluetooth devices nearby";
} else {
String subreqS = oldreqS.substring(0, length);
String leftreqS = subreqS.replace("[", "'");
String rightreqS = leftreqS.replace("]", "'");
reqS = rightreqS.replaceAll(", ", "','");
replyS = currentTimestamp
+ " SERVER: MAC addresses recieved.";
}
// gør svar klar
int dstPort = request.getPort();
InetAddress dstAdr = request.getAddress();
System.out.println(currentTimestamp
+ " SERVER: Sending reply to IP: " + dstAdr.toString()
+ " på port " + dstPort);
DatagramSocket replySocket = new DatagramSocket();
replySocket.send(new DatagramPacket(replyS.getBytes(), replyS
.getBytes().length, new InetSocketAddress(dstAdr,
dstPort)));
replySocket.close();
DbUpdater.dbUpdate(reqS);
} catch (Exception e) {
}
}
}
}
ANTENNA SENDER CLASS:
package Antenna;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.util.Vector;
public class SendRemoteDevices {
public static java.util.Date date = new java.util.Date();
public static Timestamp currentTimestamp = new Timestamp(date.getTime());
public static void runMacSender() throws IOException, InterruptedException {
Vector<String> macAdds;
macAdds = RemoteDeviceDiscovery.getMacVec();
System.out.println(currentTimestamp
+ " ANTENNA: Sending macaddresses: " + macAdds);
sendMacc(macAdds);
}
public static void sendMacc(Vector<String> macAdd) {
String request = new Vector<String>(macAdd).toString().trim();
String reply = sendReceive(request);
}
// send string and receive string
// her skal serverens addresse stå
#SuppressWarnings("resource")
public static String sendReceive(String request) {
String ip = "192.168.10.106";
String serverIP = ip; // sæt anden IP ind hvis du kører
// mellem
// to maskiner
DatagramSocket ds = null;
byte[] bytes = request.getBytes(); // husk : er seperator
// sending package after encrypting.
try {
ds = new DatagramSocket();
ds.send(new DatagramPacket(bytes, bytes.length,
new InetSocketAddress(serverIP, 6789)));
System.out.println(currentTimestamp
+ " ANTENNA: Send this to serveren: \"" + request + "\"");
System.out.println(currentTimestamp
+ " ANTENNA: Waiting for answer from Server...");
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// gør mig klar til at modtage
byte[] repBytes = new byte[1000];
DatagramPacket repGram = new DatagramPacket(repBytes, repBytes.length);
try {
ds.receive(repGram);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} // receive
// trim er nødvendigt
String reply = new String(repGram.getData()).trim();
System.out.println(currentTimestamp
+ " ANTENNA: Reply from Server: \"" + reply + "\"");
try { // fordi den ikke printer ovenstående før menuen
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
return reply;
}
}
Related
I wonder how to change my program so that several clients can connect.
The server is to take the numbers from the clients and calculate the average and then return the value.
Is it enough to make a list to write down the numbers and then calculate the mean or is there any other way to solve this problem?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
private final static String HOST = "localhost";
private final static int PORT = 2300;
private final static Scanner SCANNER = new Scanner(System.in);
private static Socket socket;
private static PrintWriter out;
private static BufferedReader in;
private boolean isRunning;
public Client() {
isRunning = true;
}
public void makeRequests() {
while (isRunning) {
try {
socket = new Socket(HOST, PORT);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Input number: ");
int requestedNumber = SCANNER.nextInt();
out.println(requestedNumber);
String response = in.readLine();
System.out.println("Response: " + response);
if (response.equals("The number is correct!")) {
System.out.println("Closing the client.");
System.exit(1);
}
} catch (UnknownHostException e) {
System.out.println("Could not find host.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Could not get a response.");
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Client client = new Client();
client.makeRequests();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class Server extends Thread {
private String serverName;
private ServerSocket ss;
private BufferedReader in;
private PrintWriter out;
private int randomNumber;
private volatile boolean isRunning;
public Server(String serverName, ServerSocket ss) {
this.serverName = serverName;
this.ss = ss;
System.out.println("Server started: " + serverName + "listening at port: " + ss.getLocalPort());
isRunning = true;
randomNumber = generateRandomNumber(10);
start(); // Uruchomienie wątku
}
public int generateRandomNumber(int range) {
return new Random().nextInt(range);
}
public void run() {
while (isRunning) {
try {
Socket connection = ss.accept();
System.out.println("Connection established on server: " + serverName);
serviceRequests(connection);
} catch (IOException e) {
System.out.println("Connection closed.");
e.printStackTrace();
}
}
try {
ss.close();
System.out.println("Connection closed.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void serviceRequests(Socket connection) throws IOException {
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
out = new PrintWriter(connection.getOutputStream(), true);
try {
int requestNumber = Integer.parseInt(in.readLine());
if (requestNumber > this.randomNumber) {
System.out.println("The client guessed: " + requestNumber + ". Too high");
makeResponse("too high.");
} else if (requestNumber < this.randomNumber) {
System.out.println("The client guessed: " + requestNumber + ". Too low.");
makeResponse("too low.");
} else {
System.out.println("The client guessed: " + requestNumber);
System.out.println("CONGRATULATIONS, CORRECT!");
makeResponse("correct!");
ss.close();
}
} catch (NumberFormatException e) {
System.out.println("Could not parse request to integer.");
}
}
private void makeResponse(String message) throws IOException {
out.println("The number is " + message);
}
public static void main(String[] args) {
try {
InetSocketAddress isa = new InetSocketAddress("localhost", 2300);
ServerSocket ss = new ServerSocket();
ss.bind(isa);
new Server("test", ss);
} catch (IOException e) {
System.out.println("Could not create server socket.");
e.printStackTrace();
}
}
}
I wanted to program an chat server with sockets. I wanted , that at least two but theoretically even more can connect and chat in one big "room".
I have 2 classes for this, one server and one client class. But somehow they can only chat with themself.
The Server:
package Threads.tcp;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ChatServer {
private static int PORT = 10023;
public static List<Socket> verbindungen = new ArrayList<>();
public static List<Thread> threads = new ArrayList<>();
public static void main(String[] args) {
// Server auf Port 10023 horchen lassen
try (ServerSocket server = new ServerSocket(PORT)) {
System.out.println("Echo-Server bereit am Port " + PORT);
while (true) {
// Auf ankommende Verbindung warten, accept() blockiert so
lange
Socket verbindung = server.accept();
verbindungen.add(verbindung);
Thread t = new Thread(new Client(verbindung));
threads.add(t);
t.start();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
The Client:
package Threads.tcp;
import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class Client implements Runnable {
protected List<String> clientList = new ArrayList();
protected int ID;
protected Socket verbindung;
public Client( Socket verbindung) throws IOException {
this.verbindung = verbindung;
}
#Override
public void run() {
// Client-Thread (z.B. EchoHandler.java) ausgelagert werden.
Writer w = null;
try {
w = new OutputStreamWriter(verbindung.getOutputStream(),
Charset.forName("utf-8"));
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(w);
Reader r = null;
try {
r = new InputStreamReader(verbindung.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(r);
try {
System.out.println("Verbindung angenommen von " +
verbindung.getRemoteSocketAddress());
w.write("Hallo dies ist der Chat Server der 3ci" + "\r\n");
w.flush();
w.write("Bitte /quit zum beenden):\r\n");
w.flush();
w.write("Welchen Spitznamen moechtest du haben: ");
w.flush();
BufferedReader name = new BufferedReader(new
InputStreamReader(verbindung.getInputStream()));
String clientName;
do {
clientName = name.readLine();
if (clientList.contains(clientName)) {
w.write("Der Spitzname ist schon vergeben waehle einen
anderen: ");
w.flush();
}
} while (clientList.contains(clientName));
// Add name to list
clientList.add(clientName);
ID = clientList.size() - 1;
w.write(clientList.get(ID) + " hat den Raum betreten." + "\r\n");
w.flush();
while (true) {
// Eingabeaufforderung senden und Zeile einlesen
bw.write(clientList.get(ID) + ">");
bw.flush();
String zeile = br.readLine();
if (zeile.equals("/quit")) {
clientList.remove(ID);
break;
}
if (zeile.trim().isEmpty()) {
bw.write("\r\n");
bw.flush();
} else {
zeile += "\r\n";
bw.write(zeile);
}
}
System.out.println("Verbindung beendet mit " +
verbindung.getRemoteSocketAddress());
verbindung.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I connected my clients with PUTTY and I used RAW , because I am programming on windows.
I hope you guys can help.
Regards Lukas.
I'm writing a simple mail client that needs to do the following:
Establish a TCP connection with a mail server.
Send/receive messages to/from the mail server.
Close the connection with the mail server.
So far, my client will setup a connection just fine, but when it tries to send "HELO" + my InetAddress, the host says the domain name is invalid.
How do I resolve this so that I can send email via my mail client?
Here is my code:
package main;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MailClient {
private static int port;
private static String mailServer;
private Socket sock;
private DataInputStream inputStream;
private DataOutputStream outputStream;
private BufferedReader br;
//private OutputStreamWriter osw;
private PrintWriter pw;
public MailClient(String mailServer, int port) {
this.mailServer = mailServer;
this.port = port;
}
// Establish TCP connection with mail server
public void setUpConnection() {
System.out.println("Setting up connection to server...\n");
try {
sock = new Socket(mailServer, port);
inputStream = new DataInputStream(sock.getInputStream());
outputStream = new DataOutputStream(sock.getOutputStream());
br = new BufferedReader(new InputStreamReader(inputStream));
pw = new PrintWriter(outputStream);
//osw = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
if(readResponse() == 220) {
System.out.println("Connection established!\n");
}
} catch (UnknownHostException e) {
System.err.println("Host name" + mailServer + " isn't recognized\n");
} catch (IOException e) {
System.err.println("I/O for host " + mailServer + " failed.\n");
}
}
// Dialogue with mail server using SMTP
public void sendMessage(String from, String to, String subject, String message) {
System.out.println("Sending message to server...\n");
try {
String response;
writeMsg("HELO " + InetAddress.getLocalHost().getHostName() + "\n");
readResponse();
writeMsg("MAIL FROM: " + from + "\n");
readResponse();
writeMsg("RCPT TO: " + to + "\n");
readResponse();
writeMsg("DATA\n");
readResponse();
writeMsg("From: " + from + "\n");
writeMsg("To: " + to + "\n");
writeMsg("Date: " + "\n");
writeMsg("Subject: " + subject + "\n");
writeMsg(message + "\n");
writeMsg("\n.\n");
readResponse();
writeMsg("QUIT");
readResponse();
System.out.println("Message sent!");
String responseFromServer;
while((responseFromServer = br.readLine()) != null) {
System.out.println("Server response: " + responseFromServer);
if(responseFromServer.indexOf("Ok") != -1) {
System.out.println("Ok recieved from mail server!");
break;
}
}
closeConnection();
} catch (IOException e) {
e.printStackTrace();
}
}
// Close TCP connection
private void closeConnection() {
System.out.println("Closing connection to server...");
try {
br.close();
pw.close();
inputStream.close();
outputStream.close();
sock.close();
System.out.println("Connection to mail server closed.");
}catch(IOException e) {
System.err.println(e);
}
}
private int readResponse() throws IOException {
String line = br.readLine();
System.out.println("Server Response:" + line + "\n");
line = line.substring(0, line.indexOf(" "));
return Integer.parseInt(line);
}
private void writeMsg(String message) {
pw.println(message);
pw.flush();
System.out.println("Message to server: " + message);
}
public static void main(String[] args) {
String emailAddress = "test#domain.edu";
String subject = "test";
String message = "hello world";
String test= "mailserver.edu";
MailClient mc = new MailClient(test, 587);
mc.setUpConnection();
mc.sendMessage("example#yahoo.com", emailAddress, subject, message);
}
}
The verbatim error I'm getting: 501 5.5.4 Invalid domain name
I have problem with filetransfer using SocketChannels: client ends to transfer the file, but the server still wait more byte from client. This causes a timeout, and the file will be saved less than a small part. The server remains stucked here: "fileChannel.transferFrom(socketChannel, 0, fileLength);".
Everything that happens before is working properly.
server:
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import javax.imageio.ImageIO;
public class RequestHandler implements Runnable {
private SocketChannel socketChannel;
BufferedReader stringIn;
public RequestHandler(SocketChannel socketChannel) {
this.socketChannel = socketChannel;
// this.serverSocketChannel = socketChannel;
System.out.println("RequestHandler initialized");
}
public static int getLastPush(String dir) {
return new File("./" + dir).listFiles().length + 1;
}
public void run() {
LoadConfig config = null;
try {
config = new LoadConfig();
} catch (IOException e) {
e.printStackTrace();
}
String type = null;
try {
socketChannel.socket().setSoTimeout(10000);
MainServer.log("Client connected from: " + socketChannel);
// Prendere immagine
DataInputStream dis = new DataInputStream(socketChannel.socket().getInputStream());
// Leggo string
stringIn = new BufferedReader(new InputStreamReader(socketChannel.socket().getInputStream()));
// Invio al client
DataOutputStream dos = new DataOutputStream(socketChannel.socket().getOutputStream());
// leggo in ricezione
MainServer.log("Attendo auth");
String auth = stringIn.readLine();
// check auth
MainServer.log("Auth ricevuto: " + auth);
String pass = config.getPass();
if (pass.equals(auth)) {
dos.writeBytes("OK\n");
System.out.println("Client Authenticated");
type = stringIn.readLine();
System.out.println("fileType: " + type);
dos.writeBytes(type + "\n");
Integer i = getLastPush(config.getFolder());
String fileName = i.toString();
System.out.println("fileName: " + fileName);
switch (type) {
case "img":
// transfer image
int len = dis.readInt();
System.out.println("Transfer started.");
byte[] data = new byte[len];
dis.readFully(data);
System.out.println("Transfer ended.");
File toWrite = new File(config.getFolder() + "/" + fileName + ".png");
ImageIO.write(ImageIO.read(new ByteArrayInputStream(data)), "png", toWrite);
dos.writeBytes("http://" + config.getDomain() + "/" + toWrite.getName());
break;
case "file":
// transfer file
System.out.println("Transfer started.");
readFileFromSocket(config.getFolder() + "/" + fileName + ".zip");
System.out.println("Transfer ended.");
System.out.println("Sending link...");
dos.writeBytes("http://" + config.getDomain() + "/" + fileName + ".zip");
break;
default:
}
i++;
System.out.println("Chiudo");
dos.close();
dis.close();
stringIn.close();
} else {
dos.writeBytes("Invalid Id or Password");
System.out.println("Invalid Id or Password");
dos.close();
dis.close();
stringIn.close();
}
socketChannel.close();
} catch (Exception exc) {
exc.printStackTrace();
}
System.out.println("----------");
}
public void readFileFromSocket(String fileName) {
RandomAccessFile aFile = null;
try {
aFile = new RandomAccessFile(fileName, "rw");
FileChannel fileChannel = aFile.getChannel();
long fileLength = Long.parseLong(stringIn.readLine());
System.out.println("File length: " + fileLength);
fileChannel.transferFrom(socketChannel, 0, fileLength);
fileChannel.close();
Thread.sleep(1000);
fileChannel.close();
System.out.println("End of file reached, closing channel");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
client:
import java.awt.AWTException;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import javax.imageio.ImageIO;
public class Uploader {
private BufferedImage img;
private byte[] bytes;
private SocketChannel socketChannel;
private String link;
private String fileName;
DataOutputStream dos;
// Per gli screen parziali
public Uploader(Rectangle r, String ip, int port) throws IOException, AWTException {
SocketChannel socketChannel = createChannel(ip, port);
this.socketChannel = socketChannel;
Rectangle screenRect = new Rectangle(0, 0, 0, 0);
for (GraphicsDevice gd : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) {
screenRect = screenRect.union(gd.getDefaultConfiguration().getBounds());
}
this.img = new Robot().createScreenCapture(screenRect).getSubimage(r.x, r.y, r.width, r.height);
ByteArrayOutputStream outputArray = new ByteArrayOutputStream();
ImageIO.write(img, "png", outputArray);
outputArray.flush();
this.bytes = outputArray.toByteArray();
outputArray.close();
}
// Per gli screen completi
public Uploader(BufferedImage bi, String ip, int port) throws IOException {
SocketChannel socketChannel = createChannel(ip, port);
this.socketChannel = socketChannel;
this.img = bi;
ByteArrayOutputStream outputArray = new ByteArrayOutputStream();
ImageIO.write(img, "png", outputArray);
outputArray.flush();
this.bytes = outputArray.toByteArray();
outputArray.close();
}
// Per i file
public Uploader(String fileName, String ip, int port) throws UnknownHostException, IOException {
SocketChannel socketChannel = createChannel(ip, port);
this.socketChannel = socketChannel;
// this.socket = new Socket(ip, port);
this.fileName = fileName;
}
public void send(String pass, String type) throws IOException {
dos = new DataOutputStream(socketChannel.socket().getOutputStream());
BufferedReader stringIn = new BufferedReader(new InputStreamReader(socketChannel.socket().getInputStream()));
try {
socketChannel.socket().setSoTimeout(10000);
// send auth
System.out.println("Sending auth");
dos.writeBytes(pass + "\n");
System.out.println("Auth sent: " + pass);
this.link = stringIn.readLine();
// this.link = os.println();
System.out.println("Auth reply: " + link);
if (this.link.equals("OK")) {
System.out.println("Sending type: " + type);
dos.writeBytes(type + "\n");
// Controllo e aspetto che il server abbia ricevuto il type
// corretto
if (stringIn.readLine().equals(type)) {
System.out.println("Il server riceve un: " + type);
switch (type) {
// image transfer
case "img":
System.out.println("Uploading image...");
dos.writeInt(bytes.length);
dos.write(bytes, 0, bytes.length);
dos.flush();
break;
// file transfer
case "file":
sendFile(fileName);
break;
// default case, hmm
default:
break;
}
// return link
System.out.println("Waiting link...");
this.link = stringIn.readLine();
System.out.println("Returned link: " + link);
bytes = null;
} else {
System.out.println("The server had a bad interpretation of the fileType");
}
} else {
System.out.println("Closed");
}
dos.close();
stringIn.close();
socketChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public SocketChannel createChannel(String ip, int port) {
SocketChannel socketChannel = null;
try {
socketChannel = SocketChannel.open();
SocketAddress socketAddress = new InetSocketAddress(ip, port);
socketChannel.connect(socketAddress);
System.out.println("Connected, now sending the file...");
} catch (IOException e) {
e.printStackTrace();
}
return socketChannel;
}
public void sendFile(String fileName) {
RandomAccessFile aFile = null;
try {
File file = new File(fileName);
aFile = new RandomAccessFile(file, "r");
FileChannel inChannel = aFile.getChannel();
long bytesSent = 0, fileLength = file.length();
System.out.println("File length: " + fileLength);
dos.writeBytes(fileLength + "\n");
// send the file
while (bytesSent < fileLength) {
bytesSent += inChannel.transferTo(bytesSent, fileLength - bytesSent, socketChannel);
}
inChannel.close();
Thread.sleep(1000);
System.out.println("End of file reached..");
aFile.close();
System.out.println("File closed.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public String getLink() {
return link;
}
}
You're losing data in the BufferedReader. If you look at the file that has been received you'll see that part of it is missing at the beginning.
You can't mix buffered and unbuffered input on the same channel. I suggest you use a DataInputStream and use read/writeUTF() to transfer the filename, andread/writeLong() to transfer the length.
I can't imagine why you're using different code to transfer images and other files. It's all bytes.
my client breaks, because of "Stream closed" exception.
Server properly waits for connection, but client don't send any data because of "stream closed" Exception.
Server after waiting time echoes "Unexpected error".
Thanks for help!
My code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static final int PORT = 50000;
static boolean flaga = true;
private static ServerSocket serverSocket;
private static Socket clientSocket;
public static void main(String[] args) throws IOException {
serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
System.err.println("Could not listen on port: " + PORT);
System.exit(1);
}
System.out.print("Wating for connection...");
Thread t = new Thread(new Runnable() {
public void run() {
try {
while (flaga) {
System.out.print(".");
Thread.sleep(1000);
}
} catch (InterruptedException ie) {
//
}
System.out.println("\nClient connected on port " + PORT);
}
});
t.start();
clientSocket = null;
try {
clientSocket = serverSocket.accept();
flaga = false;
} catch (IOException e) {
System.err.println("Accept failed.");
t.interrupt();
System.exit(1);
}
final PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
final BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
t = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
while (true) {
out.println("Ping");
System.out.println(System.currentTimeMillis()
+ " Ping sent");
String input = in.readLine();
if (input.equals("Pong")) {
System.out.println(System.currentTimeMillis()
+ " Pong received");
} else {
System.out.println(System.currentTimeMillis()
+ " Wrong answer");
}
Thread.sleep(5000);
}
} catch (Exception e) {
System.err.println(System.currentTimeMillis()
+ " Unexpected Error");
}
}
});
t.start();
}
}
And Client code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
private static final int PORT = 50000;
private static final String HOST = "127.0.0.1";
public static void main(String[] args) throws IOException {
Socket socket = null;
try {
socket = new Socket(HOST, PORT);
} catch (Exception e) {
System.err.println("Could not connect to " + HOST + ":" + PORT);
System.exit(1);
}
final PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
final BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
Thread t = new Thread(new Runnable() {
public void run() {
long start = System.currentTimeMillis();
try {
while (true) {
try {
String input = in.readLine();
if (input != null) {
System.out.println(System.currentTimeMillis()
+ " Server: " + input);
}
if (input.equals("Ping")) {
if (System.currentTimeMillis() - start > 30000) {
out.println("Pon g");
System.out.println(System
.currentTimeMillis()
+ " Client: Pon g");
break;
}
out.println("Pong");
System.out.println(System.currentTimeMillis()
+ " Client: Pong");
} else {
System.out.println(start);
out.println("got");
}
} catch (IOException ioe) {
System.err.println(System.currentTimeMillis() + " "
+ ioe.getMessage());
ioe.getStackTrace();
System.exit(0);
}
}
} catch (Exception e) {
System.err.println(System.currentTimeMillis()
+ " Unexpected Error");
}
}
});
t.start();
out.close();
in.close();
socket.close();
}
}
In your client, you start the thread but directly close streams and socket:
t.start();
out.close();
in.close();
socket.close();
You can, as a test, move the stream and socket calls to the last catch block.
...
} catch (Exception e) {
System.err.println(System.currentTimeMillis()
+ " Unexpected Error");
out.close();
in.close();
socket.close();
}
}
});
t.start();
}