Unable to receive data on server side (Java Socket Programming) - java

A single client connects to a single server.
I'm unable to display the text sent from the client.
Am I not sending the text properly from client or not receiving the text properly on Server?
Is there another way to check from the code? (on client side that the data has been sent) or (on server side that the data has been received)
package com.company;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
public class ChatServer {
public static void main(String[] args) throws IOException {
ChatServer chatServer = new ChatServer();
chatServer.go();
}
private void go() throws IOException {
//Generate a random number and write to a text file
Random randomGenerator = new Random();
int randomInt = 1024 + randomGenerator.nextInt(64511);
PrintWriter printWriter = new PrintWriter("port.txt");
printWriter.write(String.valueOf(randomInt));
printWriter.flush();
//Create Server on a port using that random number
ServerSocket serverSocket = new ServerSocket(randomInt);
System.out.println("Server on Port: "+randomInt);
//Start Accepting Clients
ClientHandler clientHandler= new ClientHandler(serverSocket);
Thread t = new Thread(clientHandler);
t.start();
}
private class ClientHandler implements Runnable {
ServerSocket serverSocket;
BufferedReader bufferedReader;
PrintWriter writer;
Socket socket;
public ClientHandler(ServerSocket sSocket) throws IOException {
serverSocket = sSocket;
}
public void run() {
while (true)
{
String message;
try {
//Accept A connection and assign a socket for this client
socket = serverSocket.accept();
System.out.println("Connection Established");
//Read Message
InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
while( (message = bufferedReader.readLine()) != null)
{
//Display it on the console
System.out.println("From Client: " + message);
//Send it back to the client
writer = new PrintWriter(socket.getOutputStream());
writer.println("Your message is: " + message);
writer.flush();
//Send your message
writer.write("This is default message");
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
This is Client Side Code
package com.company;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class ChatClient {
Socket socket;
public static void main(String[] args) throws IOException {
ChatClient chatClient = new ChatClient();
chatClient.go();
}
private void go() throws IOException {
//Read Port number from file
FileReader fileReader = new FileReader("port.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
int port = Integer.parseInt(bufferedReader.readLine());
//Connect to socket on the port number
System.out.println("Connecting to Server on: "+port);
socket = new Socket("127.0.0.1",port);
//Initiate sender thread
ChatSender chatSender = new ChatSender(socket);
Thread sender = new Thread(chatSender);
//Initiate receiver thread
ChatReceiver chatReceiver = new ChatReceiver(socket);
Thread receiver = new Thread(chatReceiver);
sender.start();
receiver.start();
}
public class ChatSender implements Runnable
{
BufferedWriter bufferedWriter;
public ChatSender(Socket socket) throws IOException {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
bufferedWriter = new BufferedWriter(outputStreamWriter);
}
public void run()
{
while (true)
{
//get text from console
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println("To Server: "+input);
try {
System.out.println("Sending data");
//write to server
bufferedWriter.write(input);
//flush the text
bufferedWriter.flush();
System.out.println("sent data");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class ChatReceiver implements Runnable
{
BufferedReader bufferedReader;
public ChatReceiver(Socket socket) throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
}
public void run()
{
try {
while (true)
{
Thread.sleep(1000);
System.out.println("Receiving data");
String output = bufferedReader.readLine();
System.out.print("From Server: "+output);
System.out.println("Received data");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Usual problem. You're reading lines, but you aren't sending lines. Change write() to println().

Related

Thread Pooled Concurrent Server (JAVA)

This is my 2nd ever Post I'm pretty new to Programming.
I'm working on making my Socket Server Concurrent (Multithreaded) on the Server side. I understand I have to use Threaded Pools after my Socket accepts but I'm just very confused what to do. currently the requests are slower then it was when it was only iterative because its not working correctly.
//MultiClient Class
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.net.*;
import java.io.*;
public class MultiServer {
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
System.out.println("What port should the server be using?");
int portNumber = scnr.nextInt();
while ((portNumber < 1025) ||(portNumber > 4998)) {
System.out.println("Please enter a Port Number between '1025' and '4998'.");
portNumber = scnr.nextInt();
}
try (ServerSocket serverSock = new ServerSocket(portNumber)){
System.out.println("Server listening on port " + portNumber);
while(true) {
Socket sock = serverSock.accept();
MultiServerHandler msh = new MultiServerHandler(sock);
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
executor.execute(msh);
}
} catch (IOException ex) {
System.out.println("Server exception: " + ex.getMessage());
ex.printStackTrace();
}
}
}
//MultiClientHandler Class
import java.io.*;
import java.net.*;
public class MultiServerHandler extends Thread{
private Socket sock;
public MultiServerHandler(Socket sock) {
this.sock = sock;
}
public void run() {
try {
System.out.println("New client connected");
InputStream input = sock.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
OutputStream output = sock.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
String command;
command = reader.readLine();
Process process = Runtime.getRuntime().exec(command);
BufferedReader read = new BufferedReader(new InputStreamReader(process.getInputStream()));
String result;
while((result = read.readLine()) != null) {
writer.println(result);
}
sock.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
So far I just know I have to implement it after the socket accepts but I'm not too sure yet.

How do i send the message to multiple clients in java Client-Server Program

Multiple Clients say(A, B, C, D etc) make connection to one server through same socket. They all send messages to server as and when required. Client messages are sent only to server(and not to other clients). But whenever server sends a message it should be delivered to all the clients. Please help me out jam only able to get server message on only 1 client
//MultithreadedServer.java
package server;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Vector;
public class MultithreadedServer
{
Vector<ClientHandler> clients = new Vector<ClientHandler>();
Vector<String> users = new Vector<String>();
private static ServerSocket servSocket;
private static final int PORT = 1247;
public MultithreadedServer() throws IOException{
servSocket = new ServerSocket(PORT);
while(true) {
Socket client = servSocket.accept();
System.out.println("\nNew client accepted.\n");
ClientHandler handler;
handler = new ClientHandler(client);
clients.add(handler);
}
}
public static void main(String[] args) throws IOException
{
MultithreadedServer ms = new MultithreadedServer();
}
class ClientHandler extends Thread
{
private Socket client;
private BufferedReader in;
private PrintWriter out;
String name,message,response;
public ClientHandler(Socket socket)
{
//Set up reference to associated socket...
client = socket;
try
{
in = new BufferedReader(
new InputStreamReader(
client.getInputStream()));
out = new PrintWriter(
client.getOutputStream(),true);
}
catch(IOException e)
{
e.printStackTrace();
}
start();
}
public void sendMessage(String msg) {
System.out.println("is it even coming here?");
out.println("Server:" + msg);
}
public void boradcast(String message) {
// send message to all connected users
for (ClientHandler c : clients) {
c.out.println("Server: hello");
}
}
public String getUserName() {
return name;
}
public void run()
{
try
{
String received;
do
{ System.out.println("Enter Your Message: ");
String msg = in.readLine();
out.println(msg);
boradcast("testing");
received = in.readLine();
out.println("ECHO: " + received);
//Repeat above until 'QUIT' sent by client...
}while (!received.equals("QUIT"));
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (client!=null)
{
System.out.println(
"Closing down connection...");
client.close();
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}
}}
//ClientProgram
import java.io.*;
import java.net.*;
public class Client
{
private static InetAddress host;
private static final int PORT = 1247;
private static Socket link;
private static BufferedReader in;
private static PrintWriter out;
private static BufferedReader keyboard;
public static void main(String[] args) throws IOException
{
try
{
host = InetAddress.getLocalHost();
link = new Socket(host, PORT);
in = new BufferedReader(
new InputStreamReader(
link.getInputStream()));
out = new PrintWriter(
link.getOutputStream(),true);
keyboard = new BufferedReader(
new InputStreamReader(System.in));
String message, response;
do
{
System.out.print(
"Enter message ('QUIT' to exit): ");
message = keyboard.readLine();
//Send message to server on
//the socket's output stream...
out.println(message);
//Accept response frm server on
//the socket's input stream...
response = in.readLine();
//Display server's response to user...
System.out.println(response);
}while (!message.equals("QUIT"));
}
catch(UnknownHostException uhEx)
{
System.out.println(
"\nHost ID not found!\n");
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
finally
{
try
{
if (link!=null)
{
System.out.println(
"Closing down connection...");
link.close();
}
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
}
}
}
An obvious way to do this would be to cycle through all ClientHandlers in clients and send the message to each of them:
for (ClientHandler ch : clients){
ch.sendMessage(message); //Or something
}

simple client - server talking to each other classes in Java

I am trying to figure out why I can send messages to the client from the server but when I try the other way around (to send messages from the client to the server) the program halts like it is waiting for some action to happen.
also how to prevent the sockets from being closed immediately.
this is the code:
Client Class
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
Client aClient = new Client();
aClient.run();
}
private Socket socket;
private PrintWriter toServer;
private BufferedReader fromServer;
public void run() {
try {
socket = new Socket("localhost", 9000);
if (socket.isConnected()){
System.out.println("CONNECTED");
}
fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toServer = new PrintWriter(socket.getOutputStream());
toServer.print("hello server");
System.out.print(fromServer.readLine());
toServer.close();
socket.close();
} catch (Exception error) {
System.out.println("CLIENT ERROR: " + error);
}
}
}
Server Class
import java.io.*;
import java.net*;
public class Server {
public static void main(String[] args) {
Server aServer = new Server();
aServer.run();
}
private ServerSocket mainSocket;
private Socket socket;
private PrintWriter toClient;
private BufferedReader fromClient;
public Server(){
try{
mainSocket = new ServerSocket(9000);
}
catch (Exception error){
System.out.print("Error :"+error);
}
}
public void run() {
System.out.println("WAITING FOR CLIENTS");
try {
socket = mainSocket.accept();
if(socket.isConnected()) {
System.out.println("CONNECTED.");
}
fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toClient = new PrintWriter(socket.getOutputStream());
System.out.println(fromClient.readLine());
toClient.print("hello Client");
toClient.close();
}
catch (Exception error) {
System.out.println("SERVER ERROR :" + error);
}
}
}
Add this before toServer.print("hello server"); to Client class. Its read from System.in and send to the Server class:
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromUser;
while((fromUser = stdIn.readLine()) != null) {
System.out.println("Client: " + fromUser);
toServer.println(fromUser);
}
And to Server class add this, before System.out.println(fromClient.readLine());, its read line from client and print to System.out:
String inputLineFromClient;
while ((inputLineFromClient = fromClient.readLine()) != null) {
System.out.println(inputLine);
}
Socket not closing before you invoke method close() or occurs some Exception.
your server is not reading anything.
use
fromClient.readLine();

Thread server/client stops after 2nd client joins

I have a server which uses multiple threads to accept multiple clients. I have it at the moment that when a client types something, it appears on the server as Client: text This works fine for 1 client. However the problem is when a second client joins.
They join fine and they can type fine. But the first client can only type 1 more thing then they stop, i.e their messages doesn't appear on the server. I presume they can do 1 as the method has been started but doesn't repeat. I've tried a while (true) loop (as seen in the code) and recalling the method at the end, neither work. I'm new to programming so don't have much expertise in this. Please find the code below :) (Note, indention is correct, just hasn't copied across properly)
Server:
package dod;
import java.net.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.io.*;
public class Server implements Runnable
{
PrintWriter out;
BufferedReader in;
Socket clientSocket;
ServerSocket serverSocket;
int portNumber;
AtomicInteger numClients = new AtomicInteger(0);
public static void main(String[] args)
{
Server s = new Server();
s.startup();
}
public void run()
{}
/**
* Start the server on the user picked port
*/
public void startup()
{
try
{
System.out.println("Enter a port");
Scanner dif = new Scanner(System.in);
portNumber = Integer.parseInt(dif.nextLine());
dif.close();
serverSocket = new ServerSocket(portNumber);
newThread();
}
catch (IOException e) {
System.out.println("Error");
System.exit(0);
}
}
public void newThread()
{
Thread thread =new Thread("C"+numClients.getAndIncrement())
{
public void run()
{
accept();
}
};
thread.start();
}
public void accept()
{
try
{
clientSocket = serverSocket.accept();
System.out.println("A new client has just connected.");
} catch(IOException e)
{
System.out.println("error");
System.exit(0);
}
newThread();
listenCommand();
}
public void listenCommand()
{
while (true)
{
try
{
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String userInput;
while ((userInput = in.readLine()) != null)
{
System.out.println("client: " + userInput);
}
} catch (IOException e)
{
System.out.println("Error");
System.exit(0);
}
}
}
}
Client:
package dod;
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String[] args) throws IOException {
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try {
Socket serverSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(serverSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
}
} catch(UnknownHostException e) {
System.out.println("error in host");
} catch(IOException e) {
System.out.println("error in IO");
}
}
}
Thank you! :)
*emphasized text*In the Server class you should have a Thread listening for new clients arriving and assigning them their own socket. You have the socket and the streams as a member variables, so everytime a new client comes you replace the socket. Also you open a new Thread for the accept connection, instead for the client itself.
Check the following (See that the client socket is another thread and I created a Runnable for it):
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;
import java.util.concurrent.atomic.AtomicInteger;
public class Server
{
ServerSocket serverSocket;
int portNumber;
AtomicInteger numClients = new AtomicInteger(0);
public static void main(String[] args)
{
Server s = new Server();
s.startup();
}
/**
* Start the server on the user picked port
*/
public void startup()
{
try
{
System.out.println("Enter a port");
Scanner dif = new Scanner(System.in);
portNumber = Integer.parseInt(dif.nextLine());
dif.close();
serverSocket = new ServerSocket(portNumber);
newThread();
}
catch (IOException e) {
System.out.println("Error");
System.exit(0);
}
}
public void newThread()
{
Thread thread =new Thread("C"+numClients.getAndIncrement())
{
public void run()
{
while(true) {
try {
accept();
} catch (Exception e) {
// lof the exception
}
}
}
};
thread.start();
}
public void accept()
{
try
{
Socket clientSocket = serverSocket.accept();
new Thread(new ClientSocket(clientSocket)).start();
System.out.println("A new client has just connected.");
} catch(IOException e)
{
System.out.println("User disconnected");
System.exit(0);
}
}
class ClientSocket implements Runnable {
Socket clientSocket;
public ClientSocket(Socket clientSocket) {
this.clientSocket = clientSocket;
}
public void run() {
{
try
{
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String userInput;
while ((userInput = in.readLine()) != null)
{
System.out.println("client: " + userInput);
}
} catch (IOException e)
{
System.out.println("Error. Probably client disconnected");
// System.exit(0); do you want to exist when a client disconnects?
}
}
}
}
}

TCP socket communication failed after the first trial

I have received error message after the client side successful received one message from server side. The error message is: Exception in thread "main" java.net.SocketException: Software caused connection abort: recv failed
It seems in client class, line = inFromserver.readLine(); would not receive any message from server, making it become "null". But I dont know why. Could somebody please help me?
Server class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class ConcurrentServer {
public static void main(String args[]) throws IOException
{
int portNumber = 20020;
ServerSocket serverSocket = new ServerSocket(portNumber);
while ( true ) {
new ServerConnection(serverSocket.accept()).start();
}
}
}
class ServerConnection extends Thread
{
Socket clientSocket;
PrintWriter outToClient;
ServerConnection (Socket clientSocket) throws SocketException
{
this.clientSocket = clientSocket;
setPriority(NORM_PRIORITY - 1);
}
public void run()
{
BufferedReader inFromClient;
try{
inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
OutputStream outToClient = clientSocket.getOutputStream();
PrintWriter printOutPut = new PrintWriter(new OutputStreamWriter(outToClient),true);
String request= inFromClient.readLine();
if(request !=null)
{
if(!request.equalsIgnoreCase("finished"))
{
printOutPut.write("Receving data");
}
else
{
printOutPut.write("file received");
}
}
}catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
try
{
clientSocket.close();
}catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
client class
import java.io.*;
import java.net.*;
import java.util.concurrent.TimeUnit;
public class client{
public static void main(String[] args) throws Exception{
final int PORT=20020;
String serverHostname = new String("127.0.0.1");
Socket socket;
PrintWriter outToServer;
BufferedReader inFromServer;
BufferedReader inFromUser;
byte[] dataToTransfer;
String line;
int counter=0;
int i=0;
socket = new Socket(serverHostname, PORT);
outToServer = new PrintWriter(socket.getOutputStream(),true);
inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
inFromUser = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Simulation of file transferring");
System.out.println("Enter the file size you want to transfer (Max Size 50MB)");
int userInput = Integer.parseInt(inFromUser.readLine());
System.out.println("Transferring start");
boolean connection = true;
while(connection)
{
//set transfer rate at 1MB/s
dataToTransfer = new byte[1000000];
Thread.sleep(1000);
if(i<userInput)
{
outToServer.println(dataToTransfer);
counter++;
System.out.println(counter + "MB file has been transferred");
}
else
{
outToServer.println("Finished");
}
line = inFromServer.readLine();
System.out.println(line);
if(!line.equalsIgnoreCase("file received"))
{
}
else
{
System.out.println("Transfer completed");
break;
}
i++;
}
outToServer.close();
inFromServer.close();
inFromUser.close();
socket.close();
}
}
You are sending byte array from client to server and reading string on server side.
Insert somthing in your byte array and then Convert your byte array into String
String str = new String(dataToTransfer,int offset, 1000000);
then write:
outToServer.println(str);

Categories