Client server messages in a loop - java

I want to send two messages at least from the client to the server and the server then responds to these messages. However only one message is sent from the client and the server also responds to one any idea where i am wrong
This is my server.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class server
{
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String sub = br.readLine();
//string parsing
String delims = "[.]";
String[] tokens = sub.split(delims);
System.out.println("You have subscribed to "+tokens[1]);
String returnMessage="Subscription message received.";
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
InputStream iss = socket.getInputStream();
InputStreamReader isrr = new InputStreamReader(iss);
BufferedReader brr = new BufferedReader(isrr);
String subb = brr.readLine();
System.out.println("Regular message received from client is "+subb);
OutputStream oss = socket.getOutputStream();
OutputStreamWriter osww = new OutputStreamWriter(oss);
BufferedWriter bww = new BufferedWriter(osww);
bww.write(subb);
System.out.println("Message sent "+subb);
bww.flush();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){}
}
}
}
And this is my client.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
public class client
{
private static Socket socket;
public static void main(String args[])
{
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the subscription message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String subscribe= "Subscribe.nust";
String sendMessage = subscribe + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
//Send the regualar message to the server
OutputStream oss = socket.getOutputStream();
OutputStreamWriter osww = new OutputStreamWriter(oss);
BufferedWriter bww = new BufferedWriter(osww);
String regular= "Because of the APS Peshawar attack that took place on 16th December 2014, nust is facing security issues.";
String sendMessage2 = regular + "\n";
bww.write(sendMessage2);
bww.flush();
System.out.println("Message sent to the server : "+sendMessage2);
//Get the return message from the server
InputStream iss = socket.getInputStream();
InputStreamReader isrr = new InputStreamReader(iss);
BufferedReader br1 = new BufferedReader(isrr);
String msg = br1.readLine();
System.out.println("Message received from the server : " +msg);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}

Don't keep creating new BufferedReaders/Writers on the same socket. Use the same ones for the life of the socket. You're losing data in their buffers.

Related

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.

Java Client/Server App will not readLine()

I am trying to write a program that allows the user to send a message to a server and receive a modified version of that message. For some reason, the flow of the program stops on a certain line below, which I have pointed out. Can anybody explain why this isn't working? Thanks.
Server Side
import java.net.*;
import java.io.*;
public class Server{
public final static int port = 1025;
public static void main (String[] args){
ServerSocket serverSocket;
Socket client;
PrintWriter output;
try{
serverSocket = new ServerSocket(port);
try{
while(true){
client = serverSocket.accept();
InputStream is = client.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from client is " + message);
String returnMessage = message + message;
OutputStream os = client.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is " + returnMessage);
bw.flush();
}
} catch(IOException e){
serverSocket.close();
System.err.println(e);
}
} catch(IOException e){
System.err.println(e);
}
}
}
Client Side
import java.util.Scanner;
import java.net.*;
import java.io.*;
class Client{
public void getService(String destination, int port){
try{
while(true)
{
Scanner in = new Scanner(System.in);
System.out.println("Send a message to the server: ");
String message = in.nextLine();
Socket server = new Socket(destination, port);
OutputStream os = server.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String sendMessage = message + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+ sendMessage);
InputStream is = server.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message2 = br.readLine(); // I have determined that the program's flow proceeds no further than this line
System.out.println("Message received from the server : " + message2);
}
} catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args){
String serverAddress = args[0];
System.out.println(serverAddress);
Client client = new Client();
client.getService(serverAddress, 1025);
}
}
The server uses a BufferedReader, whose readLine method requires an end of line delimiter, but the Client is not sending it - rather, it reads the line (with end of line delimiter stripped) and attempts to echo this message. Append a new line character to the data sent by the client so that the readLine method of the Server does not block while waiting for the line:
String returnMessage = message + message + "\n";

Java Client Server chatting program

I got a code from the internet for a Client and Server to communicate in java. I modified it a bit, so that the server and client are able to chat to each other.
Initially my client sends a message to server, then server to client, then client to server and it goes on...(one cannot send more than one message continuously to the other). For this there is a basic code put in the while loop so that the conversation goes on 1 to 1. But as i put the while loop, the message from server is not received by client. If there is no while loop(which i have commented in the code here), then first the message is sent by client to server and then server to client and the program stops.
Please help me in making the chat go endlessly.
//SERVER
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
System.out.println("Server Started and listening to the port 25000");
//while(true){
//Server is running always. This is done using this while(true) loop
//Reading the message from the client
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Received from client: "+number+"\n");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(s);
bw.flush();
System.out.println("Sent (to " + socket + ") client: "+s+"\n");
//String abc = bufferRead.readLine();
//System.out.println("SAA");
//}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){}
}
}
}
//CLIENT
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
public class Client {
private static Socket socket;
public static void main(String args[])
{
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//while(true){
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
String sendMessage = s + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Sent to server: " +sendMessage+"\n");
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
System.out.println(socket);
String message = br.readLine();
System.out.println("Received from server: "+message+"\n");
//}
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
Server.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
public class Server implements Runnable {
ServerSocket serversocket;
BufferedReader br1, br2;
PrintWriter pr1;
Socket socket;
Thread t1, t2;
String in="",out="";
public Server() {
try {
t1 = new Thread(this);
t2 = new Thread(this);
serversocket = new ServerSocket(5000);
System.out.println("Server is waiting. . . . ");
socket = serversocket.accept();
System.out.println("Client connected with Ip " + socket.getInetAddress().getHostAddress());
t1.start();;
t2.start();
} catch (Exception e) {
}
}
public void run() {
try {
if (Thread.currentThread() == t1) {
do {
br1 = new BufferedReader(new InputStreamReader(System.in));
pr1 = new PrintWriter(socket.getOutputStream(), true);
in = br1.readLine();
pr1.println(in);
} while (!in.equals("END"));
} else {
do {
br2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = br2.readLine();
System.out.println("Client says : : : " + out);
} while (!out.equals("END"));
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
new Server();
}
}
Client.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
public class Client implements Runnable {
BufferedReader br1, br2;
PrintWriter pr1;
Socket socket;
Thread t1, t2;
String in = "", out = "";
public Client() {
try {
t1 = new Thread(this);
t2 = new Thread(this);
socket = new Socket("localhost", 5000);
t1.start();;
t2.start();
} catch (Exception e) {
}
}
public void run() {
try {
if (Thread.currentThread() == t2) {
do {
br1 = new BufferedReader(new InputStreamReader(System.in));
pr1 = new PrintWriter(socket.getOutputStream(), true);
in = br1.readLine();
pr1.println(in);
} while (!in.equals("END"));
} else {
do {
br2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = br2.readLine();
System.out.println("Server says : : : " + out);
} while (!out.equals("END"));
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
new Client();
}
}
//server.java
import java.io.*;
import java.net.*;
public class server {
public static void main(String []V){
try{
ServerSocket ss = new ServerSocket(1201);
Socket s = ss.accept();
DataInputStream Din = new DataInputStream(s.getInputStream());
DataOutputStream Dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String MsgIn="",MsgOut="";
while(!MsgIn.equals("end")){
MsgIn = Din.readUTF();
System.out.println(MsgIn);
MsgOut = br.readLine();
Dout.writeUTF(MsgOut);
Dout.flush();
}
s.close();
}catch(Exception e){
}
}
}
//clients.java
import java.io.*;
import java.net.*;
import javax.xml.crypto.Data;
public class clients {
public static void main(String []S){
try{
Socket s = new Socket("192.168.0.103",1201);//my pc's ip
//Socket s = new Socket("192.168.0.100",1201);
DataInputStream Din = new DataInputStream(s.getInputStream());
DataOutputStream Dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String MsgIn="",MsgOut="";
while(!MsgIn.equals("end")){
MsgOut = br.readLine();
Dout.writeUTF(MsgOut);
MsgIn = Din.readUTF();
System.out.println(MsgIn);
}
}catch(Exception e){
}
}
}
import java.io.*;
import java.net.*;
class serversvi1
{
public static void main(String svi[])throws IOException
{
try
{
ServerSocket servsock=new ServerSocket(5510);
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the file name");
String fil=dis.readLine();
System.out.println(fil+" :is file transfer");
File myfile=new File(fil);
while(true)
{
Socket sock=servsock.accept();
byte[] mybytearray=new byte[(int)myfile.length()];
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(myfile));
bis.read(mybytearray,0,mybytearray.length);
OutputStream os=sock.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
catch(Exception saranvi)
{
System.out.print(saranvi);
}
}
}
import java.io.*;
import java.net.*;
class clientsvi1
{
public static void main(String svi[])throws IOException
{
try
{
Socket sock=new Socket("localhost",5510);
byte[] bytearray=new byte[1024];
InputStream is=sock.getInputStream();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the file name");
String fil=dis.readLine();
FileOutputStream fos=new FileOutputStream(fil);
BufferedOutputStream bos=new BufferedOutputStream(fos);
int bytesread=is.read(bytearray,0,bytearray.length);
bos.write(bytearray,0,bytesread);
System.out.println("out.txt file is received");
bos.close();
sock.close();
}
catch(Exception SVI)
{
System.out.print(SVI);
}
}
}

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 UDP server

I am new to Java programming and I am trying to create a UDP server. When I compile the code it says it could not listen to port 4722 and I would like to know why. Below is the code. I would be grateful for any advice.
import java.net.*;
import java.io.*;
public class Server
{
public static void main(String[] args) throws IOException
{
DatagramSocket serverSocket = new DatagramSocket(4722);
Socket clientSocket = null;
byte[] receiveData = new byte[1024];
byte[] sendData = new byte [1024];
boolean command = true;
try
{
serverSocket = new DatagramSocket(4722);
DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
System.out.println("Waiting for client...");
}
catch (IOException e)
{
System.err.println("Could not listen on port: 4722.");
System.exit(1);
}
DatagramPacket packet = new DatagramPacket (sendData,sendData.length,4722);
serverSocket.send(packet);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
mathematicalProtocol bbm = new mathematicalProtocol();
outputLine = bbm.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null)
{
if(inputLine.equals("Bye."))
break;
outputLine = bbm.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
You are initializing serverSocket and then making a new DatagramSocket on the same port again (and you can't do that as it's already bound on the first DatagramSocket). I.e. remove the following line:
serverSocket = new DatagramSocket(4722);
Here is a complete example of client/server UDP communication.
The server read data from a file and send each line to the client.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/**
* #author nono
*
*/
public class UDPFileSender {
static class Client implements Runnable {
// Reception socket
private DatagramSocket socket;
// UDP packet to receive data into
private DatagramPacket packet;
// Flag for initialisation
private boolean failedInit = true;
/**
* Client constructor.
* #param receptionPort
* #param packetMaxLenght
*/
public Client(int receptionPort, int packetMaxLenght) {
try {
// Create the socket using the reception port
this.socket = new DatagramSocket(receptionPort);
// Init the packet
this.packet = new DatagramPacket(new byte[packetMaxLenght],packetMaxLenght);
this.failedInit = false;
} catch (SocketException e) {
//Port already used or other error
e.printStackTrace();
}
}
#Override
public void run() {
if(failedInit){
return;
}
// Loop undefinitly
while(true){
try {
System.out.println("Waiting for packet...");
// Wait for packet
socket.receive(packet);
// Assuming you are receiving string
String msg = new String(packet.getData());
System.out.println("Received : " + msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
try {
int port = 4722;
//Start a client that can listen
new Thread(new Client(port,1024)).start();
// Creaete a reader
BufferedReader reader = new BufferedReader(new FileReader("File.txt"));
//Create a socket
DatagramSocket socket = new DatagramSocket();
// Create a packet
byte[] data = new byte[1024]; // Max length
DatagramPacket packet = new DatagramPacket(data, data.length);
// Set the destination host and port
packet.setAddress(InetAddress.getByName("localhost"));
packet.setPort(port);
String line = null;
while((line = reader.readLine()) != null){
//Set the data
packet.setData(line.getBytes());
//Send the packet using the socket
System.out.println("Sending : " + line);
socket.send(packet);
Thread.sleep(200);
}
//Close socket and file
reader.close();
socket.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
If your file contains :
Hello
World
You should see :
Waiting for packet...
Sending : Hello
Received : HelloWaiting for packet...
Sending : World
Received : World
Waiting for packet...

Categories

Resources