Issue in executing SSL TLS client server Java programs - java

I have just started studying SSL TLS in Java and written the simple client and server programs. I run the server program first, followed by the client program. On execution, the client program gives the following exception stack trace :-
Exception in thread "main" javax.net.ssl.SSLHandshakeException: no cipher suites in common
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ServerHandshaker.chooseCipherSuite(Unknown Source)
at sun.security.ssl.ServerHandshaker.clientHello(Unknown Source)
at sun.security.ssl.ServerHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readDataRecord(Unknown Source)
at sun.security.ssl.AppInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at SSLServer.main(SSLServer.java:19)
Please let me know the solution to this problem. The server and client programs are as follows :-
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
public class SSLServer {
private static final int PORT = 8080;
public static void main(String[] args) throws Exception {
SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket ss = (SSLServerSocket)ssf.createServerSocket(PORT);
SSLSocket s = (SSLSocket)ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = null;
while (((line = in.readLine()) != null)) {
System.out.println(line);
}
in.close();
s.close();
}
}
import java.io.OutputStream;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class SSLClient {
private static final String HOST = "localhost";
private static final int PORT = 8080;
public static void main(String[] args) throws Exception {
SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket s = (SSLSocket)sf.createSocket(HOST, PORT);
OutputStream out = s.getOutputStream();
out.write("\nConnection established.\n\n".getBytes());
out.flush();
int theCharacter = 0;
theCharacter = 5;
while (theCharacter != '~') // The '~' is an escape character to exit
{
out.write(theCharacter);
out.flush();
theCharacter = '~';
}
out.close();
s.close();
}
}

Let the client and server agree on a common cipher.
Add below code to both server and client.
String[] enableCipherSuite = {"SSL_DH_anon_WITH_RC4_128_MD5"};
s.setEnabledCipherSuites(enableCipherSuite);

Related

Exception in "helloworld" server and client program in socket programming

I am getting this error when I'm running my client program. I was unable to recognise the problem yet.I've changed the port numbers but there is no use. I saw the previous posts regarding the same error but I didn't figured it out.
Server.java
import java.io.*;
import java.net.*;
class Server{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(8080);
while (true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new
DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
Client.java
import java.io.*;
import java.net.*;
class Client
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 8080);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
I am getting an error when I run the client.java
Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at Client.main(Client.java:11)
Can anyone help with this error?
The Client and Server Program runs perfectly fine for me.
Can you check if there is some process already listening on that port.

Consume REST API using java - SSLHandshakeException

I am trying to consume a REST API using Java. however, when I run the code it shows me this exception.
I didn't understand what does it mean, I try to search for the solution but I can't get it :(
this is the connection code:
import javax.ws.rs.core.MediaType;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
public class connectToAPI {
public static void main(String[] args) {
try{
URL url = new URL("https://ip:port/rest/path");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String userpassword = "user:pass";
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","Basic "+
userpassword);
conn.setRequestProperty("Content-Type","application/json");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
int status = 0;
if( null != conn ){
status = conn.getResponseCode();
}
if( status != 0){
System.out.println("status!=0");
if( status == 200 ){
System.out.println("status==200");
//SUCCESS message
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
}else if(status == 401){
System.out.println("status==401");
}else if(status == 501){
System.out.println("status==501");
}else if( status == 503){
System.out.println("status==503");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
when I run the code it shows me this exception:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names matching IP address ip found
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
at alert.connectToBAM.main(connectToBAM.java:77)
Caused by: java.security.cert.CertificateException: No subject
alternative names matching IP address ip found
at sun.security.util.HostnameChecker.matchIP(Unknown Source)
at sun.security.util.HostnameChecker.match(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
... 14 more
I also tried jersey clinet:
javax.ws.rs.client.Client client = ClientBuilder.newClient();
WebTarget target = client.target("https://ip:port/rest/path");
System.out.println(
target.request(MediaType.APPLICATION_JSON).get(String.class));
it shows this error:
Exception in thread "main" javax.ws.rs.ProcessingException:
javax.net.ssl.SSLHandshakeException:
java.security.cert.CertificateException: No subject alternative names
matching IP address ip found
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:284)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:278)
at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:767)
at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
at org.glassfish.jersey.internal.Errors.process(Errors.java:229)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:414)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:765)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:428)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:324)
at alert.connectToBAM.main(connectToBAM.java:47)
Any idea? pleaseeee, it is my graduation project :(
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException
Generally these type of exceptions are occurs due to certificate verification issue of the certificate, follow the below steps :
1. Download the certificate from the browser and add it to cacerts file in the jre folder
2. we need to add some java code to verify the certificate using TrustManager.
Code is given below :
public static void trustManager()
{
try
{
TrustManager[] trustAllCerts = new TrustManager[]
{
new X509TrustManager()
{
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
#Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}
};
//Create an Instance for SSLContext class
SSLContext sc = SSLContext.getInstance("SSL");
//overload init method
sc.init(null, trustAllCerts, new java.security.SecureRandom());
//Use static method setDefaultSSLSocketFactory
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
//Create Instance for Hostname verifier and override verify() method
HostnameVerifier allHostsValid = new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1)
{
return true;
}
};
//Verify hostname using static method setDefaultHostnameVerifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
catch(Exception e)
{
e.printStackTrace();
}
}
Whenever you are trying to execute just call this method at first in main method. Hope this will help you :)

Getting connection errors while making a server/client chat program in java

I'm nowhere near done with this project yet I'm just trying to make sure things are working and more specifically that the client and server are connecting, and I'm getting connection errors. Here are my two programs. I'm also not entirely sure how to run both of them at once in eclipse so maybe that is the problem. Any help is much appreciated
import java.net.*;
import java.util.*;
import java.io.*;
public class Server {
public void main(String[] args)throws Exception {
ServerSocket server = new ServerSocket(3333);;
while (true)
{
Socket clientsocket = server.accept();
Scanner sc = new Scanner(clientsocket.getInputStream());
PrintStream p = new PrintStream(clientsocket.getOutputStream());
String message = "Hello from server";
p.print(message);
}
}
And heres the client
public static void main(String[] args)throws Exception {
Client display = new Client();
display.setVisible(true);
try {
Socket server = new Socket("localhost", 3333);
Scanner sc = new Scanner(server.getInputStream());
PrintStream p = new PrintStream(server.getOutputStream());
System.out.println(sc.next());
server.close();
sc.close();
p.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I have some gui stuff above and below the client that I didnt show. When I run these I get the following errors
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at Client.main(Client.java:56)
and line 56 is the line with -- Socket server = new Socket("localhost", 3333);

java.net.UnknownHostException not able to connect to ftp

I have ftp port as: ftp://173.201.0.1/
I am trying to connect it through following:
String Ftp_Path = "ftp://173.201.0.1/";
public List<String> GetFileList()
{
String ftpServerIP = Ftp_Path;
String ftpUserID = Ftp_UserName;
String ftpPassword = Ftp_Password;
FTPFile[] downloadFiles = null;
StringBuilder result = new StringBuilder();
FTPClient ftp = new FTPClient();
List<String> xlsFiles = null;
try {
ftp.connect(Ftp_Path);
ftp.login(ftpUserID, ftpPassword);
downloadFiles=ftp.listFiles();
xlsFiles = new ArrayList<String>();
for(FTPFile i : downloadFiles) {
if(i.toString().endsWith(".xls")) {
xlsFiles.add(i.toString());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return xlsFiles;
}
But I am getting error on line:
ftp.connect(Ftp_Path);
Following is the error.
java.net.UnknownHostException: ftp://173.201.0.1/
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at org.apache.commons.net.DefaultSocketFactory.createSocket(DefaultSocketFactory.java:92)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:201)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:289)
at com.amazonaws.mws.samples.ImportRulesPropertyClass.GetFileList(ImportRulesPropertyClass.java:33)
at com.amazonaws.mws.samples.ManageReportScheduleSample.main(ManageReportScheduleSample.java:74)
Plase help me.
I am new with java.
You just need to specify the IP.The FTPClient makes a ftp request.It is not similar to http request.Just change
String Ftp_Path = "ftp://173.201.0.1/";
to
String Ftp_Path = "173.201.0.1";
Also check whether the ftp port is up and accessible through telnet

Java multi-clients server socket getting errors

I've tried making a simple server to accept multiple sockets & then let them input and receive an output.
But it seems like I am doing it wrong as I am getting many errors.
Is the way I am trying to do that bad? How can I do that in a better way?
I dont understand why do I get these errors:
Starting up..
Trying to listen...
Server is successfully running on port 43594
New connection: /127.0.0.1:60639
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Client.getInputStream(Client.java:29)
at ClientHandler.run(ClientHandler.java:19)
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Client.getInputStream(Client.java:29)
at ClientHandler.run(ClientHandler.java:19)
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Client.getInputStream(Client.java:29)
at ClientHandler.run(ClientHandler.java:19)
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Client.getInputStream(Client.java:29)
at ClientHandler.run(ClientHandler.java:19)
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Client.getInputStream(Client.java:29)
at ClientHandler.run(ClientHandler.java:19)
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Client.getInputStream(Client.java:29)
at ClientHandler.run(ClientHandler.java:19)
And many many more lines of errors. Its basically looping the same error over and over, but why?
I've commented the code so you can see what i've tried to do and maybe fix the way I do that.
public class Server {
private int port = 43594;
public void listen() {
System.out.println("Trying to listen...");
try {
final ServerSocket server = new ServerSocket(port);
// Create new thread to handle clients I/O
ClientHandler handler = new ClientHandler(server);
// START it
handler.start();
System.out.println("Server is successfully running on port " + port);
while (true) {
// New connection found create a new Client object
Client cl = new Client(server.accept());
cl.setup();
// add it to clietns list in the I/O handler
handler.clients.add(cl);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// start up
System.out.println("Starting up..");
// server instance
final Server server = new Server();
// create a new thread for server
new Thread(new Runnable() {
#Override
public void run() {
// listen for new connections
server.listen();
}
}).start();
}
}
public class ClientHandler extends Thread {
private Thread handler;
public ArrayList<Client> clients = new ArrayList<Client>(); // client list
private ServerSocket server;
public ClientHandler(ServerSocket s) {
server = s;
}
public void run() {
while(true) {
// Loop every time through every client and see if he has wrote
// anything to do server. I am 100% sure this is wrong, how can I do this
// without using multithreads (thread per client)?
for (Client c : this.clients) {
if (c.getInputStream() != null) {
// found input, return a message.
c.sendMessage("hey client");
}
}
try {
// sleep for 100ms
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Client {
private Socket socket;
private int clientId;
private BufferedReader inStream;
private PrintWriter outStream;
private boolean socketAlive = true;
public Client(Socket sock) {
this.socket = sock;
}
public void setup() {
setInputOutputStream();
System.out.println("New connection: " + this.getIpAddress());
this.sendMessage("Successfully connected!");
}
public String getInputStream() {
String toReturn = "";
try {
toReturn = this.inStream.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return toReturn;
}
private void setInputOutputStream() {
try {
inStream = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
outStream = new PrintWriter(this.socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String s) {
this.outStream.println(s);
this.outStream.flush();
}
public String getIpAddress() {
return this.socket.getRemoteSocketAddress().toString();
}
}
And not sure if it will be useful, this is the client:
public class TestClient {
/**
* #param args
* #throws IOException
* #throws UnknownHostException
*/
public static void main(String[] args) {
try {
System.out.println("Client started");
Socket sock = new Socket("localhost", 43594);
Scanner scanner = new Scanner(System.in);
String input;
PrintWriter out = new PrintWriter(sock.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
input = scanner.nextLine();
if (input != null) {
out.print(input);
}
if (reader.toString() != null) {
System.out.println(reader.toString());
}
} catch (IOException e) {
System.out.println("Client error");
}
}
}
Why is the connection keeps getting reset?
The client has no loop or delay, so it would just immediately quit as soon as it sent data. When a program quits, the operating system always closes all of its network connections!
Also, I don't think this does what you want it to do: System.out.println(reader.toString());. Check the output of the client!
You are writing things from the server that you aren't reading at the client. Instead the client just exits after the print. 'reader.toString() doesn't do any I/O. You need to call a read method.

Categories

Resources