This is just a very Simple Server/Client application that i have written in Java with the intention using BufferedReader and BufferedWriter only.
I dont get any Errors when i start the Server.
But when the Client tries to send a message to the server:
java.net.SocketException: Connection reset
appears. I dont know why this happens but i think it could have to do something with the BufferedWriter maybe.
I searched in the Internet but i haven't found anything usefull specific to this.
Server.java
import java.io.*;
import java.net.*;
public class Server {
public Server(int port) {
try {
ServerSocket seso = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Server listening on port " + port);
Socket client1 = seso.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(client1.getInputStream(), "UTF-8"));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client1.getOutputStream(), "UTF-8"));
String s = null;
while((s = reader.readLine()) != null) {
System.out.println("Client: " + s);
}
writer.close();
reader.close();
} catch (Exception e) {e.printStackTrace();}
}
public static void main(String args[]) {
new Server(4444);
}
}
Client.java
import java.io.*;
import java.net.*;
public class Client {
public Client(String serverip) {
try {
Socket client = new Socket(serverip, 4444);
System.out.println("Client connected with: " + serverip);
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream(), "UTF-8"));
writer.write("Hello Server");
writer.flush();
}catch(Exception e){e.printStackTrace();}
}
public static void main(String args[]) {
new Client("localhost");
}
}
And when i run the server followed by the client i get this from the console:
Server started
Server listening on port 4444
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at Server.<init>(Server.java:24)
at Server.main(Server.java:33)
BUILD SUCCESSFUL (total time: 9 seconds)
If i add:
writer.newLine();
after
writer.write("Hello Server");
in Client.java i still get:
Server started
Server listening on port 4444
Client: Hello Server
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at Server.<init>(Server.java:24)
at Server.main(Server.java:33)
BUILD SUCCESSFUL (total time: 2 seconds)
Related
I have made 2 classes, one is client.java and one is server.java. I am using socket to communicate between them. The server and client connects but don't send data and stays connected.
client.java:
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost", 42069);
System.out.println("Connected to the server!");
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(s.getOutputStream()));
BufferedReader in = new BufferedReader
(new InputStreamReader(s.getInputStream()));
out.write("hi from client");
System.out.println(in.readLine());
s.close();
}
server.java:
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(42069);
System.out.println("\nWaiting For Connection...");
Socket s = ss.accept();
System.out.println("\nConnected to the client!");
BufferedReader in = new BufferedReader
(new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter
(newOutputStreamWriter(s.getOutputStream()));
System.out.println(in.readLine());
out.write("hi from server");
}
when both connect, they stay like this:
s.jaerverva
Waiting For Connection...
Connected to the client!
client.java
Connected to the server!
when i terminate the client, i get this error on the server:
Exception in thread "main" java.net.SocketException: Connection reset
at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:323)
at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:350)
at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:803)
at java.base/java.net.Socket$SocketInputStream.read(Socket.java:966)
at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:270)
at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:313)
at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:188)
at java.base/java.io.InputStreamReader.read(InputStreamReader.java:177)
at java.base/java.io.BufferedReader.fill(BufferedReader.java:162)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:329)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:396)
at HTTP.server.main(server.java:14)
Update One: Through use of a TCP port checker, I was able to verify that the port 8080 on the AWS instance is active and accepting connections.
This means that the port is likely not being bound properly somehow, will update back if I manage to resolve this issue.
Additionally, through use of the AWS server instance logs, under /var/log/nginx/error.log are entries that suggest the connection is being refused, despite the unrestricted access protocols.
I have a Socket Based Server that runs completely fine on localhost. I start the server, then instance client calls, and behaviour is as desired and expected; the server returns "Hello World" to the client and terminates the connection.
However, if I upload the server to AWS and host it as a Java application, I cannot establish a connection and reproduce the behaviour of the localhost service.
HelloWorldServer:
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 NetMiddlewareServer {
public static void main(String[] args) {
// TODO code application logic here
int portNumber = 8080;
while(true){
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
System.out.println("Test");
String inputLine, outputLine;
// Initiate conversation with client
outputLine = "Hello World";
out.println(outputLine);
clientSocket.close();
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
HelloWorldClient:
import java.io.*;
import java.net.*;
public class KKPClient {
public static void main(String[] args) throws IOException {
String hostName = "localhost";
int portNumber = 8080;
try (
Socket hwSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(hwSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(hwSocket.getInputStream()));
) {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
String fromServer;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
}
catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
The above code works completely fine locally, however uploading the Server to AWS and changing the hostName leads to errors, and I believe this is where the problem lies.
The IP address for the server instance for example, 52.214.166.199, does not connect and an IOException is thrown when trying to declare the Socket hwSocket. No input is returned as the Socket is not properly created, and so the Hello World message is not received.
Any help is greatly appreciated, thanks.
Stack Trace:
Exception in thread "main" java.net.SocketException: Socket is not connected: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at kkpclient.KKPClient.main(hwClient.java:19)
C:\Users\[me]\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
I am trying to make a java program for client-server communication
I need to initialize a server socket and a client socket.
The server socket will accept a connection from the client.
After the connection has been accepted, the input i give to the client will be submitted to the server which will tell the client if the communication was successfull or not.
This is my code :
import java.io.*;
import java.net.*;
public class ClientServer {
public static void main(Strings args[]) throws Exceptions{
/*initialize server socket*/
Socket client_socket = new Socket("localhost", 12345);
BufferedReader reader = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client_socket.getOutputStream()));
String serverMsg = null;
while ((serverMsg = reader.readLine()) != null) {
System.out.println("Client: " + serverMsg);
ServerSocket server_socket;
server_socket=new ServerSocket(12345);
while (true) {
Socket mysocket=server_socket.accept();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(mysocket.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(mysocket.getInputStream()));
writer.write("prova\n");
System.out.printls("data sent");
}
}
}
but I need to get input from keyboard, not "from the code".
Thanks a lot.
I've been trying to fix "connection reset" problem in a simple java server-client program for a while.
My scenario is like this
client program will take filename as input, then send it to server program. Server will check if that file exists in the directory. If exist then server will print "ok", otherwise "file not found"
I'm getting this execption java.net.SocketException: Connection reset
Server program
package tcpserver;
import java.net.*;
import java.io.*;
public class TCPServer {
ServerSocket serversocket;
Socket socket;
BufferedReader buffread, buffout;
String filename;
String strDir = "D:\";
private void findFile(String name) {
File fileObj = new File(strDir);
File[] fileList = fileObj.listFiles();
if (fileList != null) {
for (File indexFile : fileList) {
if (name.equalsIgnoreCase(indexFile.getName())) {
System.out.println("200 ok ");
} else {
System.out.println("File Not found");
}
}
}
}
public TCPServer() {
try {
//creating server object
serversocket = new ServerSocket(6666);
socket = serversocket.accept();
//get input stream through the socket object from buffer
buffread = new BufferedReader(new InputStreamReader(socket.getInputStream()));
filename = buffread.readLine();
findFile(filename);
} catch (IOException ex) {
//System.err.println(ex);
ex.printStackTrace();
}
}
public static void main(String[] args) {
TCPServer serverObject = new TCPServer();
}
}
Client program
package tcpclient;
import java.net.*;
import java.io.*;
public class TCPClient {
BufferedReader bffread, bffinput;
String fileInput;
public TCPClient() {
try {
//Creating socket
Socket socket = new Socket("localhost", 6666);
System.out.println("Enter filename");
bffinput = new BufferedReader(new InputStreamReader(System.in));
OutputStream outputObject = socket.getOutputStream();
} catch (Exception ex) {
System.out.println("Unhandled exception caught");
}
}
public static void main(String[] args) {
TCPClient clientObject = new TCPClient();
}
}
Exception stack
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at tcpserver.TCPServer.<init>(TCPServer.java:38)
at tcpserver.TCPServer.main(TCPServer.java:47)*
Any help/suggestion is appreciated. Thanks in advance
Your server accepts the connection, but never sends anything back. The "200 OK" message gets written to stdout, not to the socket. Then the server terminates, closing the connection. At that time the client, still waiting for data, gets the exception.
I guess you want to send "200 OK" the client. So you have to pass the socket, or at least the OutputStream of the socket to findFile(), and write the response into that.
Alternatively, and a bit cleaner: return the response string from findFile(), and send it in the calling method, so findFile() doesn't even need to know about sending the response.
You should also close the socket in the block where you open it, so that data that might still be in a buffer in memory will be sent.
Client
Your client programme is not reading anything from console and sending it over to socket.
Change it to something like this..
public TCPClient() {
try {
//Creating socket
Socket socket = new Socket("localhost", 6666);
System.out.println("Enter filename");
bffinput = new BufferedReader(new InputStreamReader(System.in));
String filename = bffinput.readLine();
OutputStream outputObject = socket.getOutputStream();
// send filename over socket output stream
outputObject.write(value.getBytes());
} catch (Exception ex) {
System.out.println("Unhandled exception caught");
}
}
I hava a problem with my code. I make a server with Java which waits for connections. When a client connects, if we(the server) send the command "showinfo", the cliend send its IP address back to the server.
The problem is that it is a multi-threaded server and many clients connect. So, if, for example, 2 clients connect to the server we have to type 2 times showinfo and then the clients give us the information. How can I make the clients respond immediately with typing "showinfo" for each one and don't wait until I type showinfo for all the clients. It's a bit tiring to type 50 times showinfo if there are 50 clients before you can execute your command. Thank you in advance (i have tried some thread synchronization and some sleep() join() commands but I haven't reach a conclusion yet I hope you can help a bit.)
Here 's the server code
import java.io.*;
import java.net.*;
import java.security.*;
public class Server implements Runnable{
private Socket server;
private static String command,info,message;
BufferedReader infromclient =null;
InputStream infromclient2=null;
DataOutputStream outtoclient =null;
static BufferedReader infrommaster=null;
private static int port=6789;
Server( Socket server ){
try{
this.server=server;
infromclient =new BufferedReader(new InputStreamReader(server.getInputStream()));
outtoclient =new DataOutputStream(server.getOutputStream());
infrommaster=new BufferedReader(new InputStreamReader(System.in));
}catch( IOException e ){
System.out.println("Exception accessing socket streams: "+e);
}
}
// main()
// Listen for incoming connections and handle them
public static void main(String[] args) {
ThreadGroup clients = new ThreadGroup("clients");
System.out.print("Waiting for connections on port " + port + "...");
System.out.println("\nIn total there are:"+clients.activeCount()+" clients\n");
try{
ServerSocket server = new ServerSocket(port);
Socket nextsocket;
// waiting for connections
while(true){
nextsocket = server.accept();
Thread client= new Thread(clients,new Server(nextsocket),"client"+(clients.activeCount()+1));
System.out.println("Client connected");
System.out.println("There are "+clients.activeCount()+" clients connected");
client.start();
}
}catch (IOException ioe){
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
public void run (){
try{
command=infrommaster.readLine();
outtoclient.writeBytes(command+"\n");
// showinfo
if(command.equals("showinfo")){
info=infromclient.readLine();
System.out.println("\nClient information\n\n" +info+"\n");
}
server.close();
}catch (IOException ioe){
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
and here is the code for the client:
import java.io.*;
import java.net.*;
import java.lang.*;
public class Client{
public static void main(String args[]) throws Exception{
String command2;
String info;
Socket clientSocket=null;
Socket scket=null;
BufferedReader inFromUser=null;
DataOutputStream outToServer=null;
BufferedReader inFromServer=null;
BufferedWriter tosite=null;
try{
clientSocket = new Socket(InetAddress.getLocalHost().getHostName(), 6789);
inFromUser =new BufferedReader(new InputStreamReader(System.in));
outToServer =new DataOutputStream(clientSocket.getOutputStream());
inFromServer =new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}catch(UnknownHostException | IOException e ){
System.out.println("Problem "+e);
}
command2=inFromServer.readLine();
System.out.println("From Server:" +command2);
// showinfo
if (command2.equals("showinfo")){
try{
InetAddress myip=InetAddress.getLocalHost();
info =("IP: " +myip.getHostAddress()+"\n");
System.out.println("\nSome system information\n" + info);
outToServer.writeBytes(info);
}catch (Exception e){
System.out.println("Exception caught ="+e.getMessage());
}
}
outToServer.flush();
outToServer.close();
inFromUser.close();
inFromServer.close();
clientSocket.close();
}
}
** the command clientSocket = new Socket(InetAddress.getLocalHost().getHostName(), 6789); means that it tests my pc(my ip in port 6789) .
If one thread is blocking on the readline, the other should eventually get control. That's the whole point of multithreading. I think I know your problem. Move the code where you are reading the input command into the run() method of the server instead. Then you should be good. I think the problem is that your threads are starting after you are polling for input.
Move these lines from the Server constructor to Server's run() method:
infromclient =new BufferedReader(new InputStreamReader(server.getInputStream()));
outtoclient =new DataOutputStream(server.getOutputStream());
infrommaster=new BufferedReader(new InputStreamReader(System.in));