Java Socket and ServerSocket not communicating - java

self explainatory, server handle the client and recognize the connection, but they can't communicate yet. here's the code:
Server Class:
import java.io.*;
import java.net.*;
import java.util.*;
public class Server{
private final int PORT=8080;
public BufferedReader fromClient;
public PrintWriter toClient;
public ServerSocket server;
public Socket clientSocketHandler;
public Server(){ //constructor
if(startServer())
System.out.println("Server Avviato...");
else
System.out.println("Errore nell'avvio del server...");
}
private boolean startServer(){
try{
server = new ServerSocket(PORT);
}catch(IOException e){
e.printStackTrace();
return false;
}
return true;
}
public void runServer(){
try{
System.out.println("Server in ascolto sulla porta " + PORT + " ...");
clientSocketHandler = server.accept();
System.out.println("Client Connesso...");
InputStreamReader isr = new InputStreamReader(clientSocketHandler.getInputStream());
fromClient = new BufferedReader(isr);
OutputStreamWriter osr = new OutputStreamWriter(clientSocketHandler.getOutputStream());
BufferedWriter bw = new BufferedWriter(osr);
toClient = new PrintWriter(bw);
}catch(IOException e){
e.printStackTrace();
}
}
}
MainServer Class:
import java.lang.*;
import java.io.*;
import java.net.*;
public class MainServer{
public static void main(String args[]){
Server s1 = new Server();
s1.runServer();
float n1,n2;
String op;
try{
s1.toClient.println("comunicazione da server");
System.out.println("Aspettando i numeri...");
n1=Float.parseFloat(s1.fromClient.readLine());
n2=Float.parseFloat(s1.fromClient.readLine());
System.out.println("Numeri accettati");
System.out.println("Aspettando operatore...");
op=s1.fromClient.readLine();
System.out.println("Operatore accettato");
}catch(IOException e){
e.printStackTrace();
}
}
}
Client class:
import java.io.*;
import java.net.*;
public class Client{
private final int PORT=8080;
private InetAddress address = InetAddress.getLoopbackAddress();
public PrintWriter toServer;
public BufferedReader fromServer;
public BufferedWriter bw;
public Socket client;
public Client(){
if(startClient())
System.out.println("Connesso al Server...");
else
System.out.println("Errore nella connessione...");
}
private boolean startClient(){
try{
client = new Socket(address, PORT);
OutputStreamWriter osw = new OutputStreamWriter(client.getOutputStream());
bw = new BufferedWriter(osw);
toServer = new PrintWriter(bw);
InputStreamReader isr = new InputStreamReader(client.getInputStream());
fromServer = new BufferedReader(isr);
}catch(IOException e){
e.printStackTrace();
return false;
}
return true;
}
}
MainClient Class:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class MainClient{
public static void main(String args[]){
Client c = new Client();
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader kBoard = new BufferedReader(isr);
String n1,n2,op;
try{
System.out.println(c.fromServer.readLine());
System.out.println("Inserisci il primo numero");
n1=kBoard.readLine();
System.out.println("Inserisci il Secondo numero");
n2=kBoard.readLine();
System.out.println("Passando i valori al server");
c.toServer.println(n1);
c.toServer.println(n2);
System.out.println("Inserisci l'operatore [+,-,/,*]");
op = kBoard.readLine();
System.out.println("Passando i valori al server");
c.toServer.println(op);
}catch(IOException e){
e.printStackTrace();
}
}
}
Sorry for the italian Strings.
It client stucks at "Connesso al Server..." and Server stucks at "Aspettando i numeri"
Help me!! :)

You should make a infinite loop (while(true) {...}) in the server socket method runServer in order to accept client sockets. Without it just doesn't listens!
In order to process more than one client you should also make it multi-threading; i.e. each time a new client is accepted launch a new thread to process the request.
Should help you out. Have a nice day...

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.

TCP Client/Server program getting stuck when

I have been working on creating a program where communication can be exchanged between a server and a client using to program files in java. However, when I try to send messages from server to client. I have been working on a project where I am trying to send a message from a server to a client. However, when I put in my message, from the server, the client seems to get stuck on sentence = inFromServer.readLine(); in the client portion of my code and I'm not sure why. I ran the debugger on this, and it seems that "sentence" takes in the value that was inputted from the client, so im not sure why it get stuck. Does anyone have an idea what the problem may be?
Here's my code for reference-
Server Code:
package com.company;
import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.util.concurrent.*;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
class threading implements Runnable {
private int portnumbers;
Socket clientsocket;
ServerSocket connectorsocket;
public threading(Socket clientsocket)
{
this.clientsocket = clientsocket;
}
public void run(){
try {
Serverstuff(this.clientsocket);
}
catch(Exception ex)
{
System.out.print("I found exception" + ex);
}
}
public void Serverstuff(Socket socketlol)
{
// File h = null;
int width = 1536;
int height = 2048;
BufferedImage image = null;
File f = null;
while(true) {
try {
String sentence1;
//Wait on welcoming socket for client
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socketlol.getInputStream()));
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream outToClient = new DataOutputStream(socketlol.getOutputStream());//create input stream, attached to socket
System.out.println("Flag1");
sentence1 = inFromUser.readLine();
System.out.println("Flag2");
System.out.println("Flag3");
outToClient.writeBytes(sentence1);
}
catch(Exception ex)
{
System.out.print("I found exception" + ex);
}
}
}
}
public class server{
public static void main(String argv[]) throws Exception {
String clientSentence;
String capitalizedSentence;
int portnumber;
Scanner scanney = new Scanner(System.in);
System.out.println("Enter the number of clients");
String arg1 = scanney.next();
int arg2 = Integer.parseInt(arg1);
int[] socketarray = new int[arg2];
for(int i = 0; i < arg2; i++) {
System.out.println("enter the port number");
String portnumberstr = scanney.next();
portnumber = Integer.parseInt(portnumberstr);
socketarray[i] = portnumber;
}
//ServerSocket welcomeSocket = new ServerSocket(5000);
int g = 0;
int whatever;
//ServerSocket welcomeSocket2 = new ServerSocket(5001);
while (true) {
if(g < arg2) {
System.out.println("Flagwhile1");
whatever = socketarray[g];
ServerSocket welcomeSocket = new ServerSocket(whatever);
System.out.println("Flagwhile2");
Socket clientsock = welcomeSocket.accept();
threading newthread = new threading(clientsock);
System.out.println("Flagwhile3");
new Thread(newthread).start();
g = g + 1;
}
}
}
}
Client Code:
package com.company;
import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.util.concurrent.*;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class client2{
public static void main(String argv[]) throws Exception {
try {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); //Create input stream
Socket clientSocket = new Socket("127.0.0.2", 5001); //Create client socket connect to server
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); //Create output stream, attached to socket
System.out.println("Flag19");
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); //Create input stream attached to socket
System.out.println("Flag20");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n'); //send line to server
System.out.println("Flag21");
sentence = inFromServer.readLine();
System.out.println("Flag22");
System.out.println(sentence);
int test = 5;
clientSocket.close();
}
catch(IOException e){
System.out.println("Error: " + e);
}
}
}

The chat client-server multithread doesn't work

image of a error:image
i am creating a multi threaded client server chat with 2 clients. The program gives no errors, but the message I send does not reach the client, how can I do it? writing
hello # client 1
the message should get to the second client but it doesn't.
how do i change the client name?
Below I leave the files respectively of the server and the client that I wrote:
import java.io.*;
import java.util.*;
import java.net.*;
public class Server{
static Vector<ClientHandler> lc = new Vector<>();
static int i = 0;
public static void main(String[] args) throws UnknownHostException, IOException{
ServerSocket ss = new ServerSocket(2104);
while (true){
Socket s = ss.accept();
System.out.println("Ricevuta nuova richiesta del client " + s);
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
ClientHandler ch = new ClientHandler(s,"Client numero" + i, dis, dos);
Thread t = new Thread(ch);
System.out.println("Il client si sta aggiungendo alla lista");
lc.add(ch);
t.start();
i++;
}
}
}
class ClientHandler implements Runnable{
Scanner scn = new Scanner(System.in);
private String name;
final DataInputStream dis;
final DataOutputStream dos;
Socket s;
boolean login;
public ClientHandler(Socket s, String name, DataInputStream dis, DataOutputStream dos){
this.dis = dis;
this.dos = dos;
this.name = name;
this.s = s;
this.login=true;
}
#Override
public void run(){
String ricevuta;
while (true){
try{
ricevuta = dis.readUTF();
System.out.println(ricevuta);
if(ricevuta.equals("logout")){
this.login=false;
this.s.close();
break;
}
StringTokenizer st = new StringTokenizer(ricevuta, "#");
String MsgToSend = st.nextToken();
String recipient = st.nextToken();
for (ClientHandler mc : Server.lc){
if (mc.name.equals(recipient) && mc.login==true){
mc.dos.writeUTF(this.name+ " : " +MsgToSend);
break;
}
}
} catch (IOException e){
e.printStackTrace();
}
}
try{
this.dis.close();
this.dos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
final static int ServerPort = 2104;
public static void main(String args[]) throws UnknownHostException, IOException{
Scanner scn = new Scanner(System.in);
InetAddress ip = InetAddress.getByName("localhost");
Socket s = new Socket(ip, ServerPort);
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
Thread sendMessage = new Thread(new Runnable(){
#Override
public void run(){
while (true){
String messaggio = scn.nextLine();
try {
dos.writeUTF(messaggio);
} catch (IOException e){
e.printStackTrace();
}
}
}
});
Thread readMessage = new Thread(new Runnable(){
#Override
public void run(){
while (true){
try {
String messaggio = dis.readUTF();
System.out.println(messaggio);
} catch (IOException e){
e.printStackTrace();
}
}
}
});
sendMessage.start();
readMessage.start();
}
}

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

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().

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