Java Client Server Socket related problem - java

import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {
String ip = "localhost";
int port = 5643;
Socket s = new Socket(ip, port);
String str = "Sagar Tanwar";
OutputStreamWriter os = new OutputStreamWriter(s.getOutputStream());
PrintWriter pw = new PrintWriter(os);
os.write(str);
os.flush();
}
}
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws Exception {
System.out.println("Server is started");
ServerSocket ss = new ServerSocket(5643);
System.out.println("Server is waiting");
Socket s = ss.accept();
System.out.println("Client Connected");
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = br.readLine();
System.out.println("Client Data : "+str);
}
}
Exception in thread "main" java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
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.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:606)
at java.net.Socket.connect(Socket.java:555)
at java.net.Socket.<init>(Socket.java:451)
at java.net.Socket.<init>(Socket.java:228)

In Client.java change this line:
String str = "Sagar Tanwar";
to:
String str = "Sagar Tanwar\r\n";
Your server expects to read a full line (br.readLine()) and it continues to read until your client stays connected. Once the client disconnects, an exception is thrown because the server was unable to read a new line.
Side notes
On my system:
your client throws: java.net.ConnectException: Connection refused: connect - if the server is not active
your server throws: java.net.SocketException: Connection reset - if the server can't read a full line from the client

Everything will work for you if you close the connections at the end of the client class.
String ip = "localhost";
int port = 5643;
Socket s = new Socket(ip, port);
String str = "Sagar Tanwar";
OutputStreamWriter os = null;
try {
os = new OutputStreamWriter(s.getOutputStream());
os.write(str);
os.flush();
} finally {
if (os != null)
os.close();
}
or with "try with resources"
String ip = "localhost";
int port = 5643;
Socket s = new Socket(ip, port);
String str = "Sagar Tanwar";
try (OutputStreamWriter os = new OutputStreamWriter(s.getOutputStream())) {
os.write(str);
os.flush();
}

import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
String ip = "localhost";
int port = 5643;
Socket s = new Socket(ip, port);
String str = "Sagar Tanwar";
OutputStreamWriter os = new OutputStreamWriter(s.getOutputStream());
PrintWriter pw = new PrintWriter(os);
os.write(str);
os.flush();
}
}

Related

Exception in thread "main" java.net.ConnectException: Connection refused: connect Socket Programming Java

I recently learn about Socket Programming between client and server. So I thought of doing an exercise of connecting both client and server. However, I have encountered this error message when I try to run the code:
Exception in thread "main" java.net.ConnectException: Connection refused: connect
This is my client class code:
public class clientpart {
public static void main(String[]args) throws UnknownHostException, IOException {
Scanner input = new Scanner(System.in);
int port = 8080;
String host=null;
String answer; String sendMessage; String receivedMessage;
InetAddress address = InetAddress.getByName(host);
Socket socket= new Socket(address,port);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
System.out.println("Please answered the following question: ");
System.out.println("What is the subject code for Socket Programming?");
answer = input.nextLine();
sendMessage = answer;
bw.write(sendMessage);
bw.newLine();
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
receivedMessage = br.readLine();
System.out.println("Message received from server : " + receivedMessage);
}
}
This is my server code:
public class serverpart {
public static Socket socket;
public static void main(String[]args) throws IOException {
int port = 8080;
String answer; String returnedMessage; String reply;
ServerSocket server = new ServerSocket(port);
System.out.println("Server start at port "+port+".");
while(true)
{
socket = server.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
answer = br.readLine();
System.out.println("Message sent from client: " + answer);
if("NET 3202".equals(answer) || "net 3202".equals(answer) || "NET3202".equals(answer) || "net3202".equals(answer)){
reply = "Correct!";
returnedMessage = reply;
}
else{
reply = "Wrong!";
returnedMessage = reply;
}
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnedMessage);
bw.newLine();
System.out.println("Message replied to client: "+returnedMessage);
bw.flush();
}
}
}
The full error message is:
Exception in thread "main" java.net.ConnectException: Connection refused: 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:244)
at clientpart.main(clientpart.java:13)
C:\Users\PeiErn\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)
I hope someone can help me, thanks.
There are 2 issues in your program:
You use the port 80 which is part of the well-known ports or system ports (0 to 1023), so you need to launch your server with the admin rights or change it for 8080 for example.
You forgot to call bw.newLine() after each bw.write(sendMessage) such that it waits for ever since on the other side you call br.readLine() which means that it waits for an entire line while you don't send the end of line characters.
Change your code for this:
Server part:
public class serverpart {
public static Socket socket;
public static void main(String[]args) throws IOException {
int port = 8080;
...
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnedMessage);
bw.newLine();
...
Output:
Server start at port 8080.
Accepted
Message sent from client: net3202
Message replied to client: Correct!
Client part:
public class clientpart {
public static void main(String[]args) throws IOException {
Scanner input = new Scanner(System.in);
int port = 8080;
...
bw.write(sendMessage);
bw.newLine();
bw.flush();
...
Output:
Please answered the following question:
What is the subject code for Socket Programming?
net3202
Message sent to server: net3202
Message received from server : Correct!

Java multi-thread chat server - sending messages [duplicate]

I recently learn about Socket Programming between client and server. So I thought of doing an exercise of connecting both client and server. However, I have encountered this error message when I try to run the code:
Exception in thread "main" java.net.ConnectException: Connection refused: connect
This is my client class code:
public class clientpart {
public static void main(String[]args) throws UnknownHostException, IOException {
Scanner input = new Scanner(System.in);
int port = 8080;
String host=null;
String answer; String sendMessage; String receivedMessage;
InetAddress address = InetAddress.getByName(host);
Socket socket= new Socket(address,port);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
System.out.println("Please answered the following question: ");
System.out.println("What is the subject code for Socket Programming?");
answer = input.nextLine();
sendMessage = answer;
bw.write(sendMessage);
bw.newLine();
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
receivedMessage = br.readLine();
System.out.println("Message received from server : " + receivedMessage);
}
}
This is my server code:
public class serverpart {
public static Socket socket;
public static void main(String[]args) throws IOException {
int port = 8080;
String answer; String returnedMessage; String reply;
ServerSocket server = new ServerSocket(port);
System.out.println("Server start at port "+port+".");
while(true)
{
socket = server.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
answer = br.readLine();
System.out.println("Message sent from client: " + answer);
if("NET 3202".equals(answer) || "net 3202".equals(answer) || "NET3202".equals(answer) || "net3202".equals(answer)){
reply = "Correct!";
returnedMessage = reply;
}
else{
reply = "Wrong!";
returnedMessage = reply;
}
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnedMessage);
bw.newLine();
System.out.println("Message replied to client: "+returnedMessage);
bw.flush();
}
}
}
The full error message is:
Exception in thread "main" java.net.ConnectException: Connection refused: 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:244)
at clientpart.main(clientpart.java:13)
C:\Users\PeiErn\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)
I hope someone can help me, thanks.
There are 2 issues in your program:
You use the port 80 which is part of the well-known ports or system ports (0 to 1023), so you need to launch your server with the admin rights or change it for 8080 for example.
You forgot to call bw.newLine() after each bw.write(sendMessage) such that it waits for ever since on the other side you call br.readLine() which means that it waits for an entire line while you don't send the end of line characters.
Change your code for this:
Server part:
public class serverpart {
public static Socket socket;
public static void main(String[]args) throws IOException {
int port = 8080;
...
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnedMessage);
bw.newLine();
...
Output:
Server start at port 8080.
Accepted
Message sent from client: net3202
Message replied to client: Correct!
Client part:
public class clientpart {
public static void main(String[]args) throws IOException {
Scanner input = new Scanner(System.in);
int port = 8080;
...
bw.write(sendMessage);
bw.newLine();
bw.flush();
...
Output:
Please answered the following question:
What is the subject code for Socket Programming?
net3202
Message sent to server: net3202
Message received from server : Correct!

How to connect to Java ServerSocket from Remote Host

Found some similar questions but no answer, so here goes -
Attached code is self contained, compilable and runnable to set up a server on my computer. Socket gets created, and I can do a telnet <ip_address> 9162 or telnet localhost 9162 from my local machine. From a remote host, telnet does not get connected. Any ideas? TIA.
import java.io.*;
import java.net.*;
public class TestServerSocket {
public static void main(String args[]) throws IOException {
final int portNumber = 9162;
System.out.println("Creating server socket on port " + portNumber);
ServerSocket serverSocket = new ServerSocket(portNumber);
while (true) {
Socket socket = serverSocket.accept();
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
while (true) {
pw.print("What's you name? ");
pw.flush();
String str = br.readLine();
if (str.trim().length() == 0)
break;
pw.println("Hello, " + str);
}
pw.close();
socket.close();
}
}
}

Java TCP sending first message, then infinite wait

My Issue based on code below:
Run TCPServer.java
then Run TCPClient.java
I expect to have the client print out
Server Said(1): HEY DUDE 1
Server Said(2): HEY DUDE 2
... but it just stays on HEY DUDE 1. What am I doing that is not producing the results I want?
TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer {
public static void main (String args[]) throws Exception{
new TCPServer();
}
TCPServer() throws Exception{
//create welcoming socket at port 6789
ServerSocket welcomeSocket = new ServerSocket(6789);
while (true) {
//block on welcoming socket for contact by a client
Socket connectionSocket = welcomeSocket.accept();
// create thread for client
Connection c = new Connection(connectionSocket);
}
}
class Connection extends Thread{
Socket connectionSocket;
Connection(Socket _connectionSocket){
connectionSocket = _connectionSocket;
this.start();
}
public void run(){
try{
//create input stream attached to socket
BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connectionSocket.getInputStream()));
//create output stream attached to socket
PrintWriter outToClient = new PrintWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
//read in line from the socket
String clientSentence = inFromClient.readLine();
System.out.println("Client sent: "+clientSentence);
//process
String capitalizedSentence = clientSentence.toUpperCase() + '\n';
//write out line to socket
outToClient.print(capitalizedSentence);
outToClient.flush();
}catch(Exception e){}
}
}
}
TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient {
//String name="";
String host = "localhost";
int port = 6789;
Socket socket = null;
public static void main(String args[]) throws Exception{
TCPClient client = new TCPClient();
client.SendToServer("Hey dude 1");
System.out.println("Server Said(1): "+client.RecieveFromServer());
client.SendToServer("Hey dude 2");
System.out.println("Server Said(2): "+client.RecieveFromServer());
client.close();
}
TCPClient(String _host, int _port) throws Exception{
host = _host;
port = _port;
socket = new Socket(host, port);
}
TCPClient() throws Exception{
socket = new Socket(host, port);
}
void SendToServer(String msg) throws Exception{
//create output stream attached to socket
PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
//send msg to server
outToServer.print(msg + '\n');
outToServer.flush();
}
String RecieveFromServer() throws Exception{
//create input stream attached to socket
BufferedReader inFromServer = new BufferedReader(new InputStreamReader (socket.getInputStream()));
//read line from server
String res = inFromServer.readLine(); // if connection closes on server end, this throws java.net.SocketException
return res;
}
void close() throws IOException{
socket.close();
}
}
Your server thread ends as soon as you process first message. You need to put server code into a loop like this:
String clientSentence;
while ((clientSentence = inFromClient.readLine()) != null) {
System.out.println("Client sent: "+clientSentence);
//process
String capitalizedSentence = clientSentence.toUpperCase() + '\n';
//write out line to socket
outToClient.print(capitalizedSentence);
outToClient.flush();
}

java DataOutputStream exception

The exception is thrown in line 24 the second time I type something (after I have typed the host name) - server works right. Code
import java.io.*;
import java.net.*;
class TCPclient {
public static void main(String[] args) throws Exception {
String hostname, msg;
InetAddress hostaddress;
BufferedReader inFromUser = new BufferedReader (new InputStreamReader(System.in));
System.out.println("Please type host\n");
hostname = inFromUser.readLine(); //I type localhost
hostaddress = InetAddress.getByName(hostname);
Socket cSocket = new Socket(hostaddress, 44444);
String cAddress = cSocket.getLocalSocketAddress().toString();
DataOutputStream outToServer = new DataOutputStream (cSocket.getOutputStream());
while (true)
{
msg = inFromUser.readLine();
System.out.println(msg);
if (msg.equals("exit"))
{
System.out.println("exit");
break;
}
outToServer.writeBytes(cAddress + " said : " + msg + '\n'); //this line throws an exception the second time it runs
}
cSocket.close();
}
}
I am new in java so I am missing something obvious I guess. Exception reads :
Exception in thread "main"
java.net.SocketException: Software
caused connection abort: socket write
error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:115)
at java.io.DataOutputStream.writeBytes(DataOutputStream.java:259)
at TCPclient.main(TCPClient.java:52) Java
Result: 1
Server :
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(44444);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream( ) ) );
clientSentence = inFromClient.readLine();
System.out.println(clientSentence + "\n");
}
}
}
Your client creates one socket and writes over and over again to that one socket. Your server, on the other hand, does this:
ServerSocket welcomeSocket = new ServerSocket(44444);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
That accepts the incoming connection, reads one line, and then abandons it (and I'm guessing on the socket's finalize when being garbage collected it closes the connection). Then it waits for a new connection.
So to fix your immediate problem, try moving
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream( ) ) );
before the while loop.
How long do you wait between typing second line? It might have something to do with socket being idle.
Also with the server code like this you will see only first message. Try this:
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(44444);
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
while (true) {
clientSentence = inFromClient.readLine();
System.out.println(clientSentence + "\n");
}
}
}
Try:
while (true)
{
if(inFromUser.readLine() != null)
{
msg = inFromUser.readLine();
System.out.println(msg);
if (msg.equals("exit"))
{
System.out.println("exit");
break;
}
outToServer.writeBytes(cAddress + " said : " + msg + "\n");
}
}
Note the changes:
if(inFromUser.readLine() != null)
{
and
... "\n");
not
... '\n');
Give it a shot. It's probably too simple a solution, but it's something :)

Categories