TCP client not responding in JAVA - java

I was learning JAVA networking API and simple TCP server-client communication.
I have written the following two classes for client and server.
The issue is that my client is not responding i.e. the program is not terminating and it doesn't output anything .. Can anyone see where I am going wrong?
Client:
import java.io.*;
import java.net.*;
public class client {
public void go() {
try {
Socket s = new Socket("127.0.0.1",2323);
InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
String reading = reader.readLine();
PrintWriter write = new PrintWriter(s.getOutputStream());
write.print("mynameistom");
System.out.println(reading);
reader.close();
writeToServer.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client;
client.go();
}
}
Server:
package TCP;
import java.io.*;
import java.net.*;
public class Server {
public void go() {
try {
ServerSocket serverSock = new ServerSocket(2323);
Socket socket = serverSock.accept();
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
String messsage = reader.readLine();
PrintWriter writer = new PrintWriter(socket.getOutputStream())
writer.println(message);
writer.close();
System.out.println(message);
} catch(IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
server.go();
}
}

The obvious thing is that the client isn't flushing, and is missing the new line.
PrintWriter writeToServer = new PrintWriter(s.getOutputStream());
writeToServer.print("network");
Should be either
PrintWriter writeToServer = new PrintWriter(s.getOutputStream(), true);
writeToServer.println("network");
or
PrintWriter writeToServer = new PrintWriter(s.getOutputStream());
writeToServer.println("network");
writeToServer.flush();

Related

Multi-threaded Server Client Address already in use

What I'm trying to do is make receiver class in the server which receives the sent messages from the client and make a sender class in the client. I'm trying to make the receiver in the server first 'cause I'll probably figure out how to do that in the client side after learning it. But doing this gives me java.net.BindException: Address already in use: JVM_Bind. I think it's because I have another Server server = new Server(); in the receiver. How do I solve this?
Server.java
package MultithreadingServerClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
ServerSocket serverSocket = new ServerSocket(3000);
Socket socket = serverSocket.accept();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
public Server() throws IOException {
}
public static void main(String[] args) {
Thread serverSender = new Thread(new ServerSender());
Thread serverReceiver = new Thread(new ServerReceiver());
serverSender.start();
serverReceiver.start();
}
}
// Sender class
class ServerSender implements Runnable {
#Override
public void run() {
try {
Server serve = new Server();
Scanner scanner = new Scanner(System.in);
String msg = "";
while (!msg.equalsIgnoreCase("exit")) {
System.out.print("Server: ");
msg = scanner.nextLine();
serve.printWriter.println(msg);
}
} catch (IOException e) {
System.err.println("Sender Error " + e);
}
}
}
class ServerReceiver implements Runnable {
#Override
public void run() {
try {
Server server = new Server();
System.out.println(server.bufferedReader.readLine());
} catch (IOException e) {
System.err.println("Receiver Error " + e);
}
}
}
Client.java
package MultithreadingServerClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
Socket socket = new Socket("localhost", 3000);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
public Client() throws IOException {
}
// Receive messages
public static void main(String[] args) {
try {
Client client = new Client();
while (true) {
System.out.println("Server: " + client.bufferedReader.readLine());
}
} catch (IOException e) {
System.out.println("Server Closed!");
}
}
}
class ClientSender implements Runnable {
#Override
public void run() {
try {
Client client = new Client();
client.printWriter.println("Test message: send to Server");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Don't create multiple instances of Server, you may create the instance in main then just pass the bufferedReader to the receiver class, and the printWriter to the sender class.
Sender class :
class ServerSender implements Runnable {
private PrintWriter writer;
public ServerSender(PrintWriter printWriter){
writer = printWriter;
}
#Override
public void run() {
try {
Scanner scanner = new Scanner(System.in);
String msg = "";
while (!msg.equalsIgnoreCase("exit")) {
System.out.print("Server: ");
msg = scanner.nextLine();
writer.println(msg);
}
} catch (IOException e) {
System.err.println("Sender Error " + e);
}
}
}
Receiver class :
class ServerReceiver implements Runnable {
private BufferedReader reader;
public ServerReceiver(BufferedReader bufferedReader){
reader = bufferedReader;
}
#Override
public void run() {
try {
System.out.println(reader.readLine());
} catch (IOException e) {
System.err.println("Receiver Error " + e);
}
}
}
Method main in Server :
public static void main(String[] args) {
Server serve = new Server();
Thread serverSender = new Thread(new ServerSender(serve.printWriter));
Thread serverReceiver = new Thread(new ServerReceiver(serve.bufferedReader));
serverSender.start();
serverReceiver.start();
}
You have two threads starting a new instance of the connection at the same port (3000). I assume that you are trying to have one thread receive a message from a server and another one for sending a message to client. I don't think you need to have a design like this. This can be done in a single threaded environment. There is no need for client (sender & receiver) and server (sender & receiver).
ServerSocket.accept(); method will listen to all the message incoming to the specified port number.
In order for the server to send reply to the client . You can use
DataOutputStream.writeUTF() & DataOutputStream.flush() method.
The same goes for client side. Have a look at the program below.
class Server {
public static void main(String args[]) throws IOException {
try (ServerSocket serverSocket = new ServerSocket(3333); // open connection at port 3333
Socket socket = serverSocket.accept();
DataInputStream inputStream = new DataInputStream(socket.getInputStream());) {
DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String messageFromClient = "", messageToBeClient = "";
while (!messageFromClient.equals("exit")) {
messageFromClient = inputStream.readUTF();
System.out.println("Message From Client : " + messageFromClient);
messageToBeClient = reader.readLine();
outStream.writeUTF(messageToBeClient);
outStream.flush();
}
}
}
}
class Client {
public static void main(String args[]) throws Exception {
try (Socket socket = new Socket("localhost", 3333); // establish connection to the open socket at port 3333
DataInputStream inputStream = new DataInputStream(socket.getInputStream());) {
DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String messageFromServer = "", messageToServer = "";
while (!messageToServer.equals("exit")) {
messageToServer = reader.readLine();
outStream.writeUTF(messageToServer);
outStream.flush();
messageFromServer = inputStream.readUTF();
System.out.println("Message From Server : " + messageFromServer);
}
}
}
}

PrintWriter won't write

I have the following problem.
I programmed a simple Echo Server and Echo Client but the problem is that in the loop of the Server, where I read from the Buffered Reader, the programme stuck and it won't write.
import java.net.*;
import java.util.*;
import java.io.*;
public class SimpleServer {
public static void main(String[] args) {
System.out.println("Dies ist ein simpler Echo Server");
int port = 6000;
try {
ServerSocket server = new ServerSocket(port);
//server.setSoTimeout(30000);
System.out.println("Warte auf anfrage");
Socket client = server.accept();
InputStream is = client.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
String message = null;
while ((message = reader.readLine())!=null) {
System.out.println("Nachricht vom Client "+message);
}
OutputStream os = client.getOutputStream();
PrintWriter writer = new PrintWriter(os);
System.out.println(message);
writer.println(message);
writer.flush();
writer.close();
} catch(IOException e) {
e.printStackTrace();
} // end of try
} // end of main
} // end of class SimpleServer
But when i put the .println() and .flush() in the loop everything works great.
import java.net.*;
import java.util.*;
import java.io.*;
public class SimpleServer {
public static void main(String[] args) {
System.out.println("Dies ist ein simpler Echo Server");
int port = 6000;
try {
ServerSocket server = new ServerSocket(port);
//server.setSoTimeout(30000);
System.out.println("Warte auf anfrage");
Socket client = server.accept();
InputStream is = client.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
OutputStream os = client.getOutputStream();
PrintWriter writer = new PrintWriter(os);
String message;
while ((message = reader.readLine())!=null) {
System.out.println("Nachricht vom Client "+message);
writer.println(message);
writer.flush();
}
writer.close();
} catch(IOException e) {
e.printStackTrace();
} // end of try
} // end of main
} // end of class SimpleServer
My question is why does it stuck in the loop ?
You are reading the inpit until end of stream before you send anything. End of stream on a socket only occurs when the peer closes the connection. The peer hasn't closed the connection, because he wants to read your reply from it.
You should echo every line as you read it, not try to assemble them all and then echo them all in one great chunk. Apart from the fact that it can't work, your technique also wastes both time and space.

Unable to get message from client in client-server program in java

I am writing a client-server program in java using TCP/IP. For the purpose, I wrote the following codes:
serversock.java:
import java.net.*;
import java.io.*;
public class serversock {
public static void main(String[] args) throws IOException
{
ServerSocket sersock = null;
try
{
sersock = new ServerSocket(10007);
}
catch (IOException e)
{
System.out.println("Can't listen to port 10007");
System.exit(1);
}
Socket clientSocket = null;
System.out.println("Waiting for connection....");
try
{
clientSocket = sersock.accept();
}
catch ( IOException ie)
{
System.out.println("Accept failed..");
System.exit(1);
}
System.out.println("Conncetion is established successfully..");
System.out.println("Waiting for input from client...");
PrintWriter output = new PrintWriter(clientSocket.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine = input.readLine();
while ( inputLine != null)
{
output.println(inputLine);
System.out.println("Server: " + inputLine);
inputLine = input.readLine();
}
input.close();
clientSocket.close();
sersock.close();
}
}
clientsock.java:
import java.util.*;
import java.io.*;
import java.net.*;
public class clientsock
{
public static void main(String[] args) throws IOException
{
Socket sock = new Socket("localhost",10007);
// Scanner scan = new Scanner(System.in);
PrintWriter output = new PrintWriter(sock.getOutputStream(),true);
BufferedReader input = new BufferedReader( new InputStreamReader(sock.getInputStream()));
String line = null;
BufferedReader stdInput = new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter data to send to server: ");
line = stdInput.readLine();
while ( (line) != "bye")
{
output.println(line.getBytes());
line = stdInput.readLine();
System.out.println("Server sends: " + input.read());
}
sock.close();
}
}
Now on running the programs I got the following output:
server:
shahjahan#shahjahan-AOD270:~/Documents/java$ java serversock
Waiting for connection....
Conncetion is established successfully..
Waiting for input from client...
Server: [B#4e25154f
shahjahan#shahjahan-AOD270:~/Documents/java$
client:
shahjahan#shahjahan-AOD270:~/Documents/java$ java clientsock
Enter data to send to server:
qwe
sdf
^Cshahjahan#shahjahan-AOD270:~/Documents/java$
The server is recieving different symbols, and client receives nothing. Please help me to solve it.
In the client replace:
output.println(line.getBytes());
with
output.println(line);

Issues with the TCP client-server program

Below is my server program,
import java.io.*;
import java.net.*;
class TwoWayServer
{
public static void main(String argv[]) throws Exception
{
ServerSocket server_socket = new ServerSocket(1234);
while(true)
{
Socket listen_socket = server_socket.accept();
BufferedReader client_input = new BufferedReader(new InputStreamReader(listen_socket.getInputStream()));
DataOutputStream dos = new DataOutputStream(listen_socket.getOutputStream());
String client_str = client_input.readLine();
System.out.println(client_str);
String st=client_str.toUpperCase();
dos.writeBytes(st);
}
}
}
And my client program is as follows,
import java.io.*;
import java.net.*;
class TwoWayClient
{
public static void main(String argv[]) throws Exception
{
BufferedReader user_input = new BufferedReader( new InputStreamReader(System.in));
Socket socket = new Socket("localhost", 1234);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
BufferedReader server_response = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String client_str = user_input.readLine();
dos.writeBytes(client_str + '\n');
String response = server_response.readLine();
System.out.println("FROM SERVER: " + response);
socket.close();
}
}
Here, if I give a string from the clientside then the server return the capitalized form of the string. But the problem is that once I have provided the string, I'm not getting any response from the server.
Kindly help.
The problem is in the server in not writing the bytes to the server with a newline character try replacing dos.writeBytes(st);
with
dos.writeBytes(st + "\n");
You may try these modifications to your code.
Server:
import java.io.*;
import java.net.*;
class TwoWayServer
{
public static void main(String argv[]) throws Exception
{
ServerSocket server_socket = new ServerSocket(1234);
while(true)
{
Socket listen_socket = server_socket.accept();
BufferedReader client_input = new BufferedReader(new InputStreamReader(listen_socket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(listen_socket.getOutputStream()));
String client_str = client_input.readLine();
System.out.println(client_str);
String st=client_str.toUpperCase();
bw.write(st + '\n');
bw.flush();
}
}
}
Client:
import java.io.*;
import java.net.*;
class TwoWayClient
{
public static void main(String argv[]) throws Exception
{
BufferedReader user_input = new BufferedReader( new InputStreamReader(System.in));
Socket socket = new Socket("localhost", 1234);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader server_response = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String client_str = user_input.readLine();
bw.write(client_str + '\n');
bw.flush();
String response = server_response.readLine();
System.out.println("FROM SERVER: " + response);
socket.close();
}
}

java.io.StreamCorruptedException: invalid stream header: 72657175

Hey I am implementing an electronic voting system based on client server chat.
When I run the server it runs without any problems but without printing as well and also the client. But as soon as I give the input to the client, it gives me the following exception and crashes. Here is the code of the server and the client. So what do u think I should do to start the engine?
package engine;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
public class Server {
ServerSocket server;
int port = 6000;
public Server() {
try {
server = new ServerSocket(6000);
} catch (IOException e) {
e.printStackTrace();
}
}
public void handleConnection(){
try {
while(true){
Socket connectionSocket;
connectionSocket = server.accept();
new ConnectionHandler(connectionSocket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
server.handleConnection();
}
}
class ConnectionHandler implements Runnable {
Socket connectionSocket;
Calendar votingStartTime;
Calendar votingEndTime;
boolean timeUp;
ObjectInputStream inFromClient;
ObjectOutputStream outToClient;
BufferedWriter outToFile;
BufferedReader inFromAdmin;
ArrayList<SingleClient> clients = new ArrayList<SingleClient>();
ArrayList<Candidate> candidates;
this is the part of the code the Exception comes from:
public ConnectionHandler(Socket socket) {
try {
this.connectionSocket = socket;
votingStartTime = new GregorianCalendar();
outToClient = new ObjectOutputStream(
connectionSocket.getOutputStream());
inFromClient = new ObjectInputStream(
connectionSocket.getInputStream());
inFromAdmin = new BufferedReader(new InputStreamReader(System.in));
startVotingSession();
Thread t = new Thread(this);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
and this is the client's main method the Exception as soon as i give the input:
public static void main(String[] args) throws Exception {
client c = new client();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
while(true){
input = br.readLine();
if(input.equals("0")){
c.register();
}else if(input.equals("1")){
c.login();
}else if(input.equals("2")){
c.listCandidates();
}else if(input.equals("3")){
c.vote();
}else if(input.equals("4")){
c.checkResults();
}else if(input.equals("5")){
c.checkFinalResults();
}else if(input.equals("6")){
c.logout();
}else {
break;
}
}
}
}
without seeing the relevant code, i would guess you are recreating the ObjectInputStream on an existing socket InputStream. you must create the object streams once per socket and re-use them until you are completely finished with the socket connection. also, you should always flush the ObjectOutputStream immediately after creation to avoid deadlock.

Categories

Resources