Connection Reset in Java - java

I've been trying to fix this error for days now. Really. I just don't get it. The code is simple enough.. Why is it not working?
public class server
{
public static void main(String[] args)
{
String fileName = null;
try
{
ServerSocket ss = new ServerSocket(9999, 3);
Socket dataSocket = ss.accept();
System.out.println("Server: Connection Established");
InputStream is = dataSocket.getInputStream();
//BufferedReader br = new BufferedReader(new InputStreamReader(is));
Scanner sc = new Scanner(dataSocket.getInputStream());
while(sc.hasNextByte())
{
System.out.println("True");
fileName = fileName+sc.next();
}
FileWriter fw = new FileWriter("server"+fileName);
while(dataSocket != null)
{
fw.write(is.read());
}
fw.flush();
dataSocket.close();
ss.close();
/*String[] nameParts;
nameParts = fileName.split(".");
File f = new File(nameParts[0]+"."+nameParts[1]);
FileOutputStream fos = new FileOutputStream(f);
System.out.println(nameParts[0]);*/
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Above is the server code. The client code is below:
public class client
{
public static void main(String[] args)
{
// Read a file
try
{
Socket dataSocket = new Socket();
dataSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(), 9999));
System.out.println("Client: Connection Established");
OutputStream os = dataSocket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String fileName = "text.txt";
pw.write(fileName);
File f = new File(fileName);
Scanner sc = new Scanner(f);
/*while(sc.hasNextInt())
{
pw.write(sc.nextInt());
}*/
//pw.flush();
//pw.close();
//dataSocket.close();
/*String[] nameParts = new String[2];
nameParts = args[0].split(".");
while(sc.hasNextByte())
{
os.write(sc.nextByte());5
}*/
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
At first, both client and server just kept waiting for each other to speak, like two shy teenagers. After a few changes, this started to happen. I get the Connection Reset error. Please help. Deadlines!

sc.hasNextByte() remains true until the peer has closed the connection. So you will never get out of this loop. You need to send the filename length ahead of the filename, so you know how much of the incoming data is the filename. Then read the filename, open the file, and read and copy the rest of the stream until EOS.

Optionally, you can write your file name with a lien as below:
pw.write(fileName + "\n");
Or user some writer to writeLine(fileName ).
And in server side, use bufferedReader to read line by line:
while ((line = br.readLine()) != null) {
....
}
Then it can finish the loop if the client is closed.

Related

Sent file with socket in java

I want to send file from client to server using socket.
But at the server, I only receive the first line. What is the problem?
Server Code
public static void main(String ars[]){
int port = 1000;
try {
ServerSocket sercoc = new ServerSocket(port);
System.out.println("dkjd");
while (true){
Socket soc = sercoc.accept();
InputStream flux = soc.getInputStream();
BufferedReader entree = new BufferedReader(new InputStreamReader(flux));
String message = entree.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Client Code
public static void main(String args[]){
String hote = "127.00.0.1";
int port = 1000;
FileReader input = null;
File file = new File("src/view/files/temperature2.txt");
Socket soc = null;
try {
soc = new Socket(hote,port);
OutputStream flux = soc.getOutputStream();
OutputStreamWriter sortie = new OutputStreamWriter(flux);
try {
input = new FileReader("src/view/files/temperature2.txt");
char c;
while ((c = (char) input.read()) != -1){
sortie.write(c);
//sortie.write("\n");
}
} finally {
if (input != null){
input.close();
}
}
sortie.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
If I use BufferedReader I found errors and I can't receive anything!
in my code I have implemented the transfer of photo, txt and zip files through ObjectOutputStream and ObjectInputStream.
code:
// output
ObjectOutputStream objectOutput = new ObjectOutputStream(connection.clientSocket.getOutputStream());
objectOutput.writeObject(your_file);
// input
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
buffer = (byte[]) ois.readObject();

Some issues with sockets in Java

I'm beginning with sockets for my very first time.
I'm trying to set up a server that its only function is to give back to the client a string i send.
The client doesn't send the string, and the server doesn't receive it. Here it goes the code:
Server code:
package servidor;
//All imports needed
public class Servidor {
public static void main (String[] args){
try{
ServerSocket socketServidor = new ServerSocket(2000);
Socket socketDatos = socketServidor.accept();
PrintWriter escribirCliente = new PrintWriter(socketDatos.getOutputStream(),true);
BufferedReader leerCliente = new BufferedReader(new InputStreamReader(socketDatos.getInputStream()));
String linea;
while((linea = leerCliente.readLine())!= null){
System.out.println("hola");
System.out.println("Server: "+ linea);
escribirCliente.println(linea);
if(linea.equals("x")){
break;
}
}
socketDatos.close();
escribirCliente.close();
leerCliente.close();
socketServidor.close();
} catch (IOException e){
System.out.println("Fallo en la conexion.");
}
}
}
Client code:
package cliente;
//All imports needed
public class Cliente {
public static void main(String[] args) throws IOException{
Socket socket = new Socket("localhost", 2000);
BufferedReader leerServidor = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter escribirServidor = new PrintWriter(socket.getOutputStream());
BufferedReader teclado = new BufferedReader(new InputStreamReader(System.in));
String linea = teclado.readLine();
//System.out.println(""+linea);
while (!(linea.equals("x"))){
System.out.println("en while");
escribirServidor.println(linea);
System.out.println("eco: "+ leerServidor.readLine());
linea = teclado.readLine();
}
escribirServidor.close();
leerServidor.close();
teclado.close();
socket.close();
}
}
The thing is:
In the client, the execution never reaches the "eco" but it does reach the "en while". But in the server, that while is never reached. Not even printing the "hola". I supposed that the issue should be when reading the line, but i've been not able to fix it.
Any ideas?
Thank you in advance!

Java cannot read and write to socket at the same time

I am trying to build a simple multi client chat application using java sockets. The way I have gone about doing this is by having a client class that connects to a server class that waits for clients to connect and creates a new thread to deal with that client(Where the socket connection is read and written to). The client also reads from and writes to the socket connection to this thread. However, when the client wrote to the output stream of the socket, the server would not respond. A similar question here was posted:
Can you write to a sockets input and output stream at the same time?
One of the answers here says that you can read and write to a socket at the same time as long as reading from the socket is done on a separate thread.
Here is my client application:
public class Client {
Socket socket;
public static void main(String[] args) {
new Client();
}
public Client() {
try {
socket = new Socket("localhost", 4444);
new Thread() {
#Override
public void run() { //read from the input stream
try(
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
String line;
while( (line = in.readLine()) != null ) {
System.out.println("Server said: " + line);
}
} catch(IOException e) {
}
}
}.start();
//write to output stream
try(
PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
Scanner userInput = new Scanner(System.in);
){
System.out.println("Enter Something: ");
if(userInput.hasNextLine()) {
out.println(userInput.nextLine());
}
} catch (IOException e) {
}
} catch(IOException e) {
}
}
}
And my server application:
public class Server {
ServerSocket ss;
public static void main(String[] args) {
new Server();
}
public Server() {
System.out.println("Server Running...");
try {
ss = new ServerSocket(4444);
while(true) {
Socket socket = ss.accept();
new Thread() { //create new thread connection to client
#Override
public void run() {
new Thread() { //thread that reads inputstream
#Override
public void run() {
try(
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
String line;
while( (line = in.readLine()) != null ) {
System.out.println("Client said: " + line);
//The problem seems to lie here.
}
} catch(IOException e) {
}
}
}.start();
//write to outputstream
try (
PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
) {
String sendToClient = "Hey, my name is Server007 B)";
out.println(sendToClient);
} catch(IOException e) {
}
}
}.start();
}
} catch (IOException e) {}
}
}
I will run the server, then run the client, on the client side the output is
Server said: Hey, my name is Server007
Enter something:
Hello! <- enter anything
but the server does not print 'Client said: Hello!' like I expected it to. I hope I made my problem clear enough, thanks.
Ok, so I figured it out, I will answer my own question in case anyone makes the same mistake. The PrintWriter constructor should be this:
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Not this:
PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
Alternatively, I could have done this:
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
I must have just gotten confused between BufferedWriter and PrintWriter :P

Java Server And Client Socket Need Fix

Hello, I am new to java socket programming and I was just looking to see if somebody could give me some help.
I will post the code for the client and server then i will explain my problem...
reader = new BufferedReader(new InputStreamReader(socket.getInputStream));
while(running)
{
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
stream = new PrintStream(socket.getOutputStream());
stream.println("return: " + line);
}
}
}catch(IOException e)
{
System.out.println("Socket in use or not available: " + port);
}
}
public static void main()
{
run();
}
//Client
public static String ip;
public static int port;
public static Socket socket;
public static PrintStream stream;
public static BufferedReader reader;
public static void main(String args[])
{
try
{
socket = new socket(ip, port);
stream = new PrintStream(socket.getOutputStream());
stream.println("test0");
reader = new BufferedReader(new InputStreamReader(socket.getInputStream));
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
}
stream.println("test1");
line = reader.readLine();
if(line != null)
{
System.out.println(line);
}
}catch(IOException e)
{
System.out.println("could not connect to server!");
}
}
So my problem is even if I get rid of the loop and try to make it send the string twice it won't send it. It will only do it once unless I close and make a new socket on the client side. So if anybody could give me an explanation to what I am doing wrong that would be great, and thank you so much.
Why are you openning your outstream inside your loop?
stream = new PrintStream(socket.getOutputStream());
Take this statement outside the loop and write to your stream inside your loop.
Please keep it simple,
Try using InputStream, InputStreamReader, BufferedReader, OutputStream, PrintWriter.
Client Side:
Socket s = new Socket();
s.connect(new InetSocketAddress("Server_IP",Port_no),TimeOut);
// Let Timeout be 5000
Server Side:
ServerSocket ss = new ServerSocket(Port_no);
Socket incoming = ss.accept();
For Reading from the Socket:
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
boolean isDone = false;
String s = new String();
while(!isDone && ((s=br.readLine())!=null)){
System.out.println(s); // Printing on Console
}
For Writing to the Socket:
OutputStream os = s.getOuptStream();
PrintWriter pw = new PrintWriter(os)
pw.println("Hello");
Make sure you flush the output from your server:
stream.flush();
Thanks a lot to everybody who answered but i figures out what it was all along.
i read through some of the Oracle socket stuff and figured out that the server was supposed to be the first to send a message than the client receive and send and receive... so on and so forth so i will post my new code here in hopes somebody else trying to figure out the same thing can find it with ease
//Client
public static String ip;
public static int port;
public static Socket socket;
public static PrintWriter print;
public static BufferedReader reader;
public Client(String ip, int port)
{
this.ip = ip;
this.port = port;
//initiate all of objects
try
{
socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), 5000);
print = new PrintWriter(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//start connection with server
String line = reader.readLine();
System.out.println(line);
} catch (IOException e)
{
e.printStackTrace();
}
}
//quick method to send message
public void sendMessage(String text)
{
print.println(text);
print.flush();
try
{
String line = reader.readLine();
System.out.println(line);
} catch (IOException e)
{
e.printStackTrace();
}
}
}
public static void main(String args[])
{
client.sendMessage("test");
client.sendMessage("test2");
client.sendMessage("test3")
}
//Server
public static int port = 9884;
public static boolean running = true;
public static ServerSocket serverSocket;
public static Socket socket;
public static PrintWriter writer;
public static BufferedReader reader;
public static void run()
{
try
{
serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
writer = new PrintWriter(socket.getOutputStream(), true);
writer.println("connection");
while(running)
{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
writer.println(line);
writer.flush();
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
run();
}

Printing on Printronix T5000r over ethernet using Java

I have a problem with printing on this specific printer.
public void print(String fileName, String printerIp) {
try {
BufferedReader streamIn = new BufferedReader(new FileReader(fileName));
String line;
Socket socket = new Socket(printerIp, 9100);
Writer writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while ((line = streamIn.readLine()) != null) {
writer.write(line);
}
writer.flush();
socket.close();
streamIn.close();
}
The situation looks like everything is fine but the printer do not print, when I use other program to print everything works fine.
Any thoughts ?
The solution is to write whole file to the printer.
public void printFile(File file, String printerIp) throws PrintException, IOException {
Socket socket = new Socket(printerIp, 9100);
FileInputStream fileInputStream = new FileInputStream(file);
byte [] mybytearray = new byte [(int)file.length()];
fileInputStream.read(mybytearray,0,mybytearray.length);
OutputStream outputStream = socket.getOutputStream();
outputStream.write(mybytearray,0,mybytearray.length);
//Curious thing is that we have to wait some time to make more prints.
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
outputStream.flush();
outputStream.close();
socket.close();
fileInputStream.close();
}

Categories