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);
}
}
}
Related
i am coding a multi client chat server.i have a server folder that contains Server.java and three client folders namely client1,client2,client3 containing java files resp.now when every client joins the server i try to send a text but the server does not picks the message.the problem is in the void run() try method. till the while(true) loop everything works.
Server code:
Chat.java
import java.net.*;
import java.io.*;
import java.util.*;
class Chat implements Runnable {
Socket skt = null;
DataInputStream dis = null;
DataOutputStream dos = null;
PrintWriter pw = null;
TreeMap<Socket, String> tm;
public Chat(Socket skt, TreeMap<Socket, String> tm) {
this.skt = skt;
this.tm = tm;
}
public void run() {
try {
dis = new DataInputStream(skt.getInputStream());
String msg = "";
while (true) {
msg = dis.readUTF();
Set s = tm.keySet();
Iterator itr = s.iterator();
while (itr.hasNext()) {
String k = (String) itr.next();
Socket v = (Socket) tm.get(k);
dos = new DataOutputStream(v.getOutputStream());
dos.writeUTF();
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
dis.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
Server.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.TreeMap;
class Server
{
public static void main(String dt[])
{
ServerSocket sskt=null;
Socket skt=null;
DataInputStream dis=null;
DataOutputStream dos=null;
TreeMap <String,Socket>tm=new TreeMap<String,Socket>();
try
{
sskt=new ServerSocket(1234);
System.out.println("Waiting for Clients");
while(true)
{
skt=sskt.accept();
dis=new DataInputStream(skt.getInputStream());
dos=new DataOutputStream(skt.getOutputStream());
String user=dis.readUTF();
String pass=dis.readUTF();
if(user.equals(pass))
{
dos.writeBoolean(true);
tm.put(user,skt);
Chat ch=new Chat(skt,tm);
Thread t=new Thread(ch);
t.start();
}
else
{
dos.writeBoolean(false);
}
} //end of while.
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
try
{
dos.close();
dis.close();
skt.close();
sskt.close();
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
}
Client Code:
Send.java
import java.io.*;
import java.net.*;
class Send implements Runnable {
Socket skt = null;
public Send(Socket skt) {
this.skt = skt;
System.out.println(skt);
}
public void run() {
InputStreamReader isrout = null;
BufferedReader brout = null;
PrintWriter pw = null;
DataInputStream dis = null;
try {
// Thread.sleep(2000);
System.out.println("Send a text");
isrout = new InputStreamReader(System.in);
brout = new BufferedReader(isrout);
pw = new PrintWriter(skt.getOutputStream(), true);
do {
String msg = brout.readLine();
pw.println(msg);
} while (!msg.equals("bye"));
} catch (Exception e) {
System.out.println(e);
} finally {
try {
pw.close();
brout.close();
isrout.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
Client1.java
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
class Client1 {
public static void main(String dt[]) {
Socket skt = null;
InputStreamReader isr = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream dis = null;
try {
skt = new Socket("127.0.0.1", 1234);
System.out.println("Connected to server");
System.out.println(skt);
isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
dos = new DataOutputStream(skt.getOutputStream());
dis = new DataInputStream(skt.getInputStream());
System.out.println("Enter a username");
String user = br.readLine();
dos.writeUTF(user);
System.out.println("Enter a password");
String pass = br.readLine();
dos.writeUTF(pass);
if (dis.readBoolean()) {
System.out.println("User Authenticated");
} else {
System.out.println("Incorrect username or password");
}
Send sn = new Send(skt);
Thread t = new Thread(sn);
t.start();
} catch (Exception e) {
System.out.println(e);
} finally {
try {
// skt.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
After writing any value using an outputstream you need to flush it to actually send it.
In the Chat and Server class where you use DataOutputStream, you need to call this after writing data.
dos.flush();
In the Client class after sending data through the PrintWriter you need to call this.
pw.flush();
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.
I tried to send message from server to client but if i send message the client needs to connect again or println again...
So how does it work?
I tried to println again from server to client but the client wont receive it.
So how to send message to a specific client at any time.
Server:
package server.server.com;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.ArrayList;
public class Server extends Thread {
private static ServerSocket serverSocket;
public static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
static InputStream is;
static OutputStream os;
static byte[] buf;
static BufferedReader reader;
static BufferedWriter writer;
static double ConsoleMessage;
public static String output;
static BufferedReader bufferedReader2;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(12345);
} catch (IOException e) {
System.out.println("Could not listen on port: 12345");
}
System.out.println("Server started. Listening to the port 12345");
while (true) {
try {
clientSocket = serverSocket.accept();
inputStreamReader = new InputStreamReader(
clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
PrintWriter out = new PrintWriter(
clientSocket.getOutputStream(), true);
InputStream inputStream = new ByteArrayInputStream(
bufferedReader.readLine().getBytes(
Charset.forName("UTF-8")));
bufferedReader2 = new BufferedReader(new InputStreamReader(
inputStream));
output = bufferedReader2.readLine();
System.out.println(output);
out.flush();
out.close();
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
Client:
client = new Socket();
client.connect(
new InetSocketAddress(
"IP-ADDRESS",
PORT),
5000);
in = new BufferedReader(
new InputStreamReader(
client.getInputStream()));
printlng = new PrintWriter(
client.getOutputStream());
printlng.println(mLongitude);
printlng.flush();
try {
if ((Response = in
.readLine()) != null) {
....
You should take a look at http://developer.android.com/google/gcm/index.html. Maybe you could take advantage of push notifications in your app.
Maybe you can do something like this
Server:
private boolean sendMessage(final String msg, final String dstIp, final int dstPort) {
DatagramSocket sendSocket = null;
try {
sendSocket = new DatagramSocket();
final InetAddress local = InetAddress.getByName(dstIp);
final int msg_length = msg.length();
final byte[] message1 = msg.getBytes();
final DatagramPacket sendPacket = new DatagramPacket(message1,
msg_length, local, dstPort);
sendSocket.send(sendPacket);
} catch (final Exception e) {
e.printStackTrace();
return false;
} finally {
if (sendSocket != null) {
sendSocket.disconnect();
sendSocket.close();
sendSocket = null;
}
}
return true;
}
Client:
public static void receiveMessage() {
if ((socket == null) || socket.isClosed()) {
socket = new DatagramSocket(BROADCAST_PORT);
socket.setSoTimeout(5000);
}
try {
idMsgs.clear();
while ((socket != null) && !socket.isClosed()) {
socket.setReuseAddress(true);
socket.setSoTimeout(10000);
try {
final byte[] receiveBuffer = new byte[sizepck];
final DatagramPacket packet = new DatagramPacket(
receiveBuffer, receiveBuffer.length);
socket.receive(packet);
} catch (final SocketTimeoutException e) {
} catch (final Throwable e) {
}
}
} catch (final Throwable e1) {
try {
Thread.sleep(TIME_RETRY);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
finally {
if (socket != null) {
socket.close();
}
}
}
I have been trying to play around with Java's Socket class and I have hit a tough spot. I have three classes: EchoServerTemplate, ConcurrentServer, and EchoClient.
I want to send a website(www.google.com) from a client to the server and then have the server return the IP address. I think I am extremely close, but I do not know how BufferedStreamer in Java works well enough to figure out the error messages.
Here is my code for all three classes:
EchoServerTemplate (This is where I want the Web Address to be translated):
import java.net.*;
import java.io.*;
public class EchoServerTemplate extends Thread
{
public static final int DEFAULT_PORT = 6007;
public static final int BUFFER_SIZE = 256;
Socket clientSocket;
EchoServerTemplate(Socket cs){
clientSocket = cs;
}
public void run(){
InputStream fromClient = null;
OutputStream toClient = null;
byte[] buffer = new byte[BUFFER_SIZE];
String printaddress = null;
try {
while(true){
PrintWriter pout = new PrintWriter(clientSocket.getOutputStream(), true);
fromClient = new BufferedInputStream(clientSocket.getInputStream());
try {
InetAddress address = InetAddress.getByName(fromClient.toString());
printaddress = address.toString();
}
catch(UnknownHostException e){
System.out.println(e);
}
toClient = new BufferedOutputStream(clientSocket.getOutputStream());
while (printaddress != null) {
toClient.write(printaddress.getBytes("UTF-8"));
toClient.flush();
printaddress = null;
}
fromClient.close();
toClient.close();
clientSocket.close();
}
}
catch (IOException ioe) {
ioe.printStackTrace();}
}
}
ConcurrentServer:
import java.io.*;
import java.net.*;
public class ConcurrentServer {
public static final int BUFFER_SIZE = 256;
public static void main(String[] args) throws IOException {
try {
int serverPortNumber = 6007;
ServerSocket sock = new ServerSocket(serverPortNumber);
while (true) {
Socket clientSocket = sock.accept();
EchoServerTemplate thread = new EchoServerTemplate(clientSocket);
thread.start();
}
}
catch (IOException ioe) {
ioe.printStackTrace();}
}
}
EchoClient:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("127.0.0.1", 6007);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: ");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to the host.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("IP Address: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
The task I accomplished before this was just having the ConcurrentServer repeat what was typed on the client. In modifying the code I may have accidentally messed something up. Here are the error messages I am receiving:
run: www.google.com Exception in thread "main"
java.net.SocketException: Connection reset at
java.net.SocketInputStream.read(SocketInputStream.java:189) at
java.net.SocketInputStream.read(SocketInputStream.java:121) at
sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283) at
sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325) at
sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177) at
java.io.InputStreamReader.read(InputStreamReader.java:184) at
java.io.BufferedReader.fill(BufferedReader.java:154) at
java.io.BufferedReader.readLine(BufferedReader.java:317) at
java.io.BufferedReader.readLine(BufferedReader.java:382) at
EchoClient.main(EchoClient.java:31) Java Result: 1 BUILD SUCCESSFUL
(total time: 4 seconds)
Any help is appreciated. If you need any more information, please let me know.
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();
}
}