I am trying to implement a simple client server program that will continuously exchange messages until client decides to stop. I found many tutorials on this topic, however I am struggling with implementing the loop correctly. The server processes the first request but does not process the others.
It is probably some silly mistake so please excuse me for asking such basic question - I am new to sockets. I would be glad for any help. I provide all the code (based on some example that I found):
Client:
public class Client {
public static void main(String argv[]) throws Exception {
talkWithServer();
}
private static void talkWithServer() throws UnknownHostException, IOException {
String sentence;
String serverResponse;
BufferedReader brClient = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 9000);
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader brServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while(true) {
sentence = brClient.readLine();
out.writeBytes(sentence + '\n');
serverResponse = brServer.readLine();
System.out.println(serverResponse);
if (serverResponse.contains("<BYE>")) {
break;
}
}
clientSocket.close();
}
}
Server:
public class Server {
public static void main(String args[]) throws Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(9000);
Protocol protocol = new Protocol();
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
String response = protocol.processInput(clientSentence);
outToClient.writeBytes(response + '\n');
}
}
}
Protocol:
public class Protocol {
public String processInput(String theInput) {
String theOutput = "> " + theInput;
return theOutput;
}
}
I simplified the example for sake of easier debugging. Thanks for any tips!
My guess is line "Socket connectionSocket = welcomeSocket.accept();"
If I remember right, this will try to accept new client everytime, and since you are connecting just one, it will wait on that line forever in second iteration.
I suggest you paste that line before the while loop.
Try below
Socket connectionSocket = welcomeSocket.accept();
while (true) {
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
String response = protocol.processInput(clientSentence);
outToClient.writeBytes(response + '\n');
outToClient.flush();
}
Related
I've written both a TCP server and a TCP client application in eclipse. The Client gets user input in the form of a string then sends it to the server who capitalizes it and sends it back. They need to keep looping until the server has received a certain number of requests in which case it closes the connection between he sockets and stops. Unfortunately it only seems to loop once. I will provide a sample output of what I'm talking about after the code.
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String argv[]) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
int requests = 0;
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader (new InputStreamReader( connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream (connectionSocket.getOutputStream());
do {
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
outToClient.flush();
requests++;
}
while(requests < 10);
outToClient.writeBytes("REQUEST LIMIT REACHED");
}
}
}
and the client
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
//Creates socket, replace the hostnmae/ip address with the ipaddress of the computer running the server application.
Socket clientSocket = new Socket("10.69.88.130", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader (clientSocket.getInputStream()));
do {
System.out.print("TO SERVER: ");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
outToServer.flush();
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
}
while (!modifiedSentence.equals("REQUEST LIMIT REACHED"));
System.out.println(modifiedSentence);
clientSocket.close();
}
}
and finally the output I'm getting
TO SERVER: testa
FROM SERVER: TESTA
TO SERVER: testb
(nothing else is displayed after this line)
Well your code is working (kind of). You get a successful run, then you restart your client without restarting the server. Your request-value does not reset to 0 and after restarting the client the first request your client does is number 10 for your server.
So why is that request comming through? Because you flush the string first and then check your counter.
I have modified your server a little bit. Maybe that is what you are looking for?
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String argv[]) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
int requests = 0;
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader (new InputStreamReader( connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream (connectionSocket.getOutputStream());
while (requests < 10) {
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase();
outToClient.writeBytes(capitalizedSentence + " Request: " + requests + '\n');
outToClient.flush();
requests++;
}
outToClient.writeBytes("REQUEST LIMIT REACHED");
requests = 0;
}
}
}
I have made a socket in Java.
This socket connects with a server.
When I start my program, the server sends a message that my socket is connected with the AEOS.
When I try to login to the server for sending some commands, then the server responds again with: status connected to AEOS version
This is not the message that I expect, normally my server must send a "response true".
Can you help me?
Thanks.
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception {
while(true) {
String sentence;
String modifiedSentence;
Socket clientSocket = new Socket("127.0.0.1", 1201);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
}
output socket
Why don't you try to read everything that server had sent? Also, need to open a new Socket every-time? Depends on your implementation. Try this:
public static void main(String[] args) {
Socket clientSocket = null;
try {
clientSocket = new Socket("127.0.0.1", 1201);
BufferedReader inFromUser = new BufferedReader(
new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String initialMessageFromServer = null;
while ((initialMessageFromServer = inFromServer
.readLine()) != null) {
System.out.println(initialMessageFromServer);
}
while (true) {
String sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
StringBuilder modifiedSentence = new StringBuilder();
String responseFromServer = null;
while ((responseFromServer = inFromServer.readLine()) != null) {
modifiedSentence.append(responseFromServer);
modifiedSentence.append('\n');
}
System.out
.println("FROM SERVER: " + modifiedSentence.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I've created a TCP Server in Java and a TCP client in Ruby. The problem is I'm not able to send more than 1 message in the same connection, Only the first message is sent while the other one is not sent.
here is the Java code
package com.roun512.tcpserver;
import java.io.*;
import java.net.*;
public class Program {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket Socket = new ServerSocket(6789);
while(true)
{
Socket connection = Socket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connection.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connection.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
capitalizedSentence = clientSentence + '\n';
outToClient.writeBytes(capitalizedSentence);
System.out.println("Sent msg");
}
}
}
And here is the client code
Client.rb
require 'socket'
class Client
def initialize()
server = TCPSocket.open("127.0.0.1", 6789)
if server.nil?
puts "error"
else
puts "connected"
end
server.puts("Hello\r\n")
sleep 2
server.puts("There\r\n")
server.close
end
end
Client.new()
I'm only receiving Hello. I have tried many other ways but none worked.
So my question is how to send more than 1 message in a single connection, Any help would be appreciated :)
Thanks in advance!
Socket.accept() waits for new connection after reading the first line.
Try the following:
public static void main(String[] args) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket Socket = new ServerSocket(6789);
while (true)
{
Socket connection = Socket.accept();
while(true)
{
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connection.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connection.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
capitalizedSentence = clientSentence + '\n';
outToClient.writeBytes(capitalizedSentence);
System.out.println("Sent msg");
}
}
}
If it works, change while (true) to some meaningful condition and don`t fotget to close the connection after the work is done.
I write simple application to communication client - server.
Sending data from client to server works perfectly. Server calculates some stuff and tries to send to client result but it doesn't work.
here's code for client:
public static void main(String argv[])
{
try
{
View view = new View();
view.printStartMessage();
view.printManual();
String input;
String output;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
do
{
if (inFromServer.ready())
{
output = inFromServer.readLine();
view.print(output);
}
input = inFromUser.readLine();
outToServer.writeBytes(input + "\n");
}
while(!"EXIT".equals(input));
clientSocket.close();
}
catch (IOException ex)
{
Logger.getLogger(TCPClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
and here's for server:
public static void main(String argv[])
{
try
{
Protocol protocol = new Protocol();
View view = new View();
String clientData;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
while ((clientData = inFromClient.readLine()) != null)
{
view.print("Odebrano: " + clientData);
if("EXIT".equals(clientData))
{
break;
}
protocol.checkUsersInput(clientData);
if(protocol.isError())
{
outToClient.writeBytes(protocol.getError());
view.printError(protocol.getError());
break;
}
if (protocol.isResultReady())
{
outToClient.writeBytes(protocol.getResult());
view.print(protocol.getResult());
}
}
break;
}
}
catch (IOException ex)
{
Logger.getLogger(TCPServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
I don't know even what generates problem, client or server.
Anyone have any idea?
Thanks from advice.
EDIT:
Ok, problem solved. Server didn't sent end line tag so readLine method just didn't know where line have ended.
I need to create a program where a peer needs to communicate with other peer. I have vaguely created a structure but it does not work. I know I am making a mistake but not able to figure out the problem. I create a server socket as a thread and create a client socket thread which will talk to the server socket thread. after I enter a port, the program does nothing...
server.java
------------
class server
{
public static void main(String argv[]) throws Exception
{
//server socket
ServerSocket server = new ServerSocket(1001);
Socket client;
while(true)
{
client = server.accept();
Thread t = new Thread(new acceptconnection(client));
t.start();
}
}
}
class acceptconnection implements Runnable
{
BufferedReader inFromClient,inn;
DataOutputStream ds;
Socket clientsocket;
acceptconnection (Socket socket) throws IOException
{
this.clientsocket = socket;
inn = new BufferedReader (new InputStreamReader(System.in));
inFromClient =new BufferedReader(new
InputStreamReader(clientsocket.getInputStream()));
ds = new DataOutputStream(clientsocket.getOutputStream());
}
#Override
public void run ()
{
try
{
String clientSentence, inp;
while(( clientSentence = inFromClient.readLine())!=null)
{
System.out.println("message from remote socket #" +
clientsocket.getRemoteSocketAddress()+ clientSentence);
inp=inn.readLine();
ds.writeBytes(inp + "\n");
ds.flush();
}
}
}
}
client.java
------------
class client
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
Socket clientSocket = null;
// ss = new ServerSocket(10002);
clientSocket = new Socket("localhost", 1001);
BufferedReader inFromUser = new BufferedReader( new
InputStreamReader(System.in));
DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
System.out.println("Enter you name:");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + "\n" );
System.out.println("Enter the port u want:");
sentence = inFromUser.readLine();
int serverport = Integer.parseInt(sentence);
Thread t = new Thread(new acceptconnection1(serverport));
t.start();
String msg;
clientSocket.close();
}
}
class acceptconnection1 implements Runnable {
BufferedReader inserver, inn;
DataOutputStream ds;
Socket socket, peersocket;
int serverport ;
Socket clientSocket = null;
acceptconnection1 (int serverport) throws IOException{
this.serverport = serverport;}
public void run () {
ServerSocket ss;
String cs,a;
try {
ss = new ServerSocket(serverport);
while(true)
{
peersocket =ss.accept();
Thread t = new Thread(new abc(peersocket) );
t.start();
}}}
class abc implements Runnable {
BufferedReader inn,inp;
DataOutputStream ds;
Socket peersocket;
public abc(Socket peersocket) throws IOException{
this.peersocket = peersocket;
inn = new BufferedReader (new InputStreamReader(System.in));
inp =new BufferedReader(new InputStreamReader(peersocket.getInputStream()));
ds = new DataOutputStream(peersocket.getOutputStream());
}
#Override
public void run()
{
String clientSentence;
Socket client = new Socket();
try {
while(( clientSentence = inp.readLine())!=null)
{
ds.writeBytes("wake up!");
//System.out.println("message=" + clientSentence);
}