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();
}
}
}
}
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 :)
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
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!
Am writing a Server, client chat program using Java Socket. Here is my code for the Server socket class.
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8085);
} catch (IOException ex) {
System.out.println("IO Error, " + ex);
System.exit(1);
}
Socket clientSocket = null;
System.out.println("Listening for incoming connections");
try {
clientSocket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Failed to accept connection " + ex);
System.exit(1);
}
System.out.println("Connection Successful");
System.out.println("Listening to get input");
PrintStream output = new PrintStream(clientSocket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = input.readLine()) != null) {
System.out.println(inputLine);
System.out.println("Server: ");
inputLine = input.readLine();
output.println(inputLine);
if (!inputLine.equals("exit")) {
} else {
break;
}
}
output.close();
input.close();
clientSocket.close();
serverSocket.close();
}
}
The client is able to make a connection and send a message to the server. The server can also receive the messages sent by the client. The problem is that when the message is sent from the server, the client does not receive the message. Here is my client socket code.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Client {
public static void main(String [] args) throws Exception
{
BufferedReader input;
PrintStream output;
BufferedReader clientInput;
try (Socket client = new Socket("127.0.0.1", 8085)) {
input = new BufferedReader(new InputStreamReader(client.getInputStream()));
output = new PrintStream(client.getOutputStream());
clientInput = new BufferedReader(new InputStreamReader(System.in));
String line;
while(true)
{
System.out.println("Client: ");
line = clientInput.readLine();
output.println("Server: " + line );
if(line.equals("quit"))
{
break;
}
}
}
input.close();
clientInput.close();
output.close();
}
}
Server side:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8085);
} catch (IOException ex) {
System.out.println("IO Error, " + ex);
System.exit(1);
}
Socket clientSocket = null;
System.out.println("Listening for incoming connections");
try {
clientSocket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Failed to accept connection " + ex);
System.exit(1);
}
System.out.println("Connection Successful");
System.out.println("Listening to get input");
PrintStream output = new PrintStream(clientSocket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = input.readLine()) != null) {
System.out.println("Client request: " + inputLine);
String resp = "some response as you need";
output.println(resp);
System.out.println("Server response: " + resp);
if (!inputLine.equals("exit")) {
} else {
break;
}
}
output.close();
input.close();
clientSocket.close();
serverSocket.close();
}
}
Client side:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
BufferedReader input;
PrintStream output;
BufferedReader clientInput;
try (Socket client = new Socket("127.0.0.1", 8085)) {
input = new BufferedReader(new InputStreamReader(client.getInputStream()));
output = new PrintStream(client.getOutputStream());
clientInput = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String inputStr = clientInput.readLine();
output.println(inputStr);
System.out.println("Client: " + inputStr);
if (inputStr.equals("quit")) {
break;
}
String serverResp = input.readLine();
output.println("Server: " + serverResp);
}
}
}
}
It is tested.
It's always a good idea to flush your output streams when you are done with them, the info you are sending may have buffered.
The server is expecting an extra line from the client input here:
while ((inputLine = input.readLine()) != null) {
System.out.println(inputLine);
System.out.println("Server: ");
inputLine = input.readLine(); // <--- here
The client is not reading from the InputStream called input it gets when it connects to the server. It is only reading the local console input from clientInput.
In the while loop in Client.java you need something like this after the quit block to get the server's response:
System.out.println("Server: " + input.readLine());
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.