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.
Related
Java Client-Server.
It is necessary to receive messages from the client in the background.
I'm trying to receive messages in the background:
public Server() throws IOException {
try {
serverSocket=new ServerSocket(1234);
fromclient= serverSocket.accept();
System.out.println("Socket created");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Socket not created");
}
try {
in = new BufferedReader(new
InputStreamReader(fromclient.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
out = new PrintWriter(fromclient.getOutputStream(),true);
String input,output;
}
Bacground part:
public void run(ServerSocket welcomeSocket) throws IOException {
Socket connectionSocket = welcomeSocket.
accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
capitalizedSentence =
clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
And send message in Client part:
Client client=new Client();
client.Connect();
client.sendToServer("text test");
Run run=new Run();
void run() throws IOException {
BufferedReader inFromUser =
new BufferedReader(
new InputStreamReader(System.in));
Socket clientSocket = new Socket ("127.0.0.1",6789);
DataOutputStream outToServer =
new DataOutputStream(
clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
sentence = inFromUser.readLine();
// while (true) {
outToServer.writeBytes(sentence + "\n");
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
//}
// clientSocket.close();
}
But nothing happens.
You opened a ServerSocket on port 1234 and then the Socket to 6789. Try to use the same port :)
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();
}
}
}
}
Below is client and server program that I wrote. Now I am confused how to send ack/nack in my program.
I saw few answers on stackoverflow but i am still confused. Can you give an example of ACK/NACK in TCP protocol using java
Client:
public class Client {
public static void main(String args[]) {
try {
Socket client = new Socket("localhost", 2222);
PrintWriter pw = new PrintWriter(client.getOutputStream(), true);
Scanner input = new Scanner(System.in);
boolean a = true;
while (a) {
//receving
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println(br.readLine());
if (input.equals("q")) {
a = false;
client.close();
}
pw.println("Client0: " + input.nextLine());
System.out.println(pw);
// System.out.println("Request sent successfully");
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
Server:
public class Server {
public static void main(String args[]) {
try {
ServerSocket ss = new ServerSocket(2222);
System.out.println("Waiting for client request");
Socket client = ss.accept();
System.out.println("Accepted connection request");
Scanner input = new Scanner(System.in);
while (true) {
// receving
InputStreamReader isr = new InputStreamReader(client.getInputStream());
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
// sending
PrintStream ps = new PrintStream(client.getOutputStream());
ps.println("Server1: " + input.nextLine());
System.out.println(ps);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Thank you
I'm delving into sockets for the first time.
The point of the project is for the client to be able to get access to a contact list (CSV) in the server by writing "getall" and exit the program through just that command ("Exit").
The problem is that the client can only write the command and receive the list once and then the server doesn't respond to the client's input anymore.
Here is the socket code for the server and client respectively:
Server:
public class CatalogueServer extends CatalogueLoader {
ServerSocket serverSocket;
ArrayList<CatalogueEntry> catalogue;
public void startServer(int port, String catalogueFile) {
catalogue = loadLocalCatalogue(catalogueFile);
try {
serverSocket = new ServerSocket(port);
while (true) {
Socket clientSocket = serverSocket.accept();
new Thread(
new Runnable() {
public void run() {
try {
InputStream inputStream = clientSocket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader BR = new BufferedReader(inputStreamReader);
OutputStream outputStream = clientSocket.getOutputStream();
PrintWriter PW = new PrintWriter(outputStream);
String clientInput;
while ((clientInput = BR.readLine()) != null) {
System.out.println(clientInput);
if (clientInput.equals("getall")) {
System.out.println(printCatalogue(catalogue));
PW.println(printCatalogue(catalogue));
PW.flush();
break;
} else if (clientInput.equals("exit")) {
clientSocket.close();
BR.close();
PW.close();
break;
} else {
PW.flush();
break;
}
}
PW.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
).start();
}
} catch (Exception i) {
i.printStackTrace();
}
}
}
Client:
public class TestClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 5253);
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader BR = new BufferedReader(inputStreamReader);
while (true) {
String clientInput;
String serverFeedback;
PrintWriter PW = new PrintWriter(outputStream);
Scanner inputScan = new Scanner(System.in, "UTF-8");
clientInput = inputScan.nextLine();
PW.println(clientInput);
PW.flush();
while ((serverFeedback = BR.readLine()) != null) {
System.out.println(serverFeedback);
}
if (clientInput.equals("exit")) {
PW.close();
socket.close();
break;
}
PW.close();
}
}
catch (IOException e){
e.printStackTrace();
}
}
}
I have tried alternating the position and renewal of the readers and writers. But I'm uncertain of where exactly the problem starts.
When you do
while ((serverFeedback = BR.readLine()) != null) {
System.out.println(serverFeedback);
}
You are reading until you reach the end of the stream, i.e. until there is nothing left. As such there is nothing after this.
If you want to reuse the connection, you have to write the code which doesn't use this pattern and only reads until it should stop reading.
My code just do a simple task send a text from client's console to server and receive a reply. But my code doesn't work though. I keep sending text to server and no reply sending back. I have done a several example that plus 2 number given from client. I do this the same way but i can't figure out what is the problem.
Server:
public class Server {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(8);
Socket client = server.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter outToClient = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String in = inFromClient.readLine(),out;
while(in!=null){
out = in+" from server";
outToClient.write(out);
outToClient.newLine();
outToClient.flush();
}
inFromClient.close();
outToClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Client:
public class Client {
public static void main(String[] args) {
try {
Socket client = new Socket("localhost", 8);
System.out.println("Connected to server");
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter outToServer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
Scanner input = new Scanner(System.in);
String strClient,strServer;
while(true){
System.out.print("Client: ");
strClient = input.nextLine();
outToServer.write(strClient);
strServer = inFromServer.readLine();
System.out.print("Server: ");
System.out.println(strServer);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
There are several problems with your code:
Your server is expecting to read a line and you're only writing text without a newline symbol:
Reading a line in server with: inFromClient.readLine()
Writing text without newline in client: outToServer.write(strClient);
Change this to outToServer.write(strClient + "\n");
You don't flush the writer of the client. Add a outToServer.flush(); after the line outToServer.write(...);
You only read 1 line in the server and don't read inside the loop again.
EDIT: To make it easier i'll post the corrected code here: (I've tried it and it works like a charm)
Client:
public class Client {
public static void main(String[] args) {
try (Socket client = new Socket("localhost", 8);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter outToServer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
Scanner input = new Scanner(System.in)) {
System.out.println("Connected to server");
String strClient,strServer;
while(true){
System.out.print("Client: ");
strClient = input.nextLine();
outToServer.write(strClient);
outToServer.newLine();
outToServer.flush();
strServer = inFromServer.readLine();
System.out.println("Server: " + strServer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server:
public class Server {
public static void main(String[] args) {
try (ServerSocket server = new ServerSocket(8);
Socket client = server.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter outToClient = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()))) {
String in = inFromClient.readLine(), out;
while(in != null){
out = in + " from server";
outToClient.write(out);
outToClient.newLine();
outToClient.flush();
in = inFromClient.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please remark that this solution uses Javas ARM (Automatic resource management) for autoclosing streams and sockets. So this will not work before java 1.7!