Trouble with sending / receiving data - java

So I am attempting to send data to myself and receive the data then print it, now I have been testing for a while and I have noticed its not sending anything, in fact, maybe it is and I am not receiving it properly, I need assistance with this please.
This is what I am using to send data
String host = "127.0.0.1";
int port = Options.port;
Socket socket = new Socket(host, port);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(msg + "\n");
bw.flush();
This is what I am using to receive, I always use this method and it never works so I would not be surprised if this was the root cause.
ServerSocket serverSocket = new ServerSocket(Options.port);
System.out.println("[Listening on port] " + Options.port);
while(true){
Socket socket = serverSocket.accept();
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println(message);
}

1) replace:
Socket socket = serverSocket.accept();
socket = serverSocket.accept();
with:
Socket socket = serverSocket.accept();
2) If this does not solve the problem, set ports as int values, without Options.port

Related

the buffer in server doesn't read the value that client sent

The client sends data (string) to the server, and the server must read it, but in my case the server didn't read the data (value) that the client sent, and I didn't know where is the problem exactly, because normally the steps to read data are all correct in the server side
Client side:
Socket socket = new Socket(address, authenticationServerPort);
username = username + "\n"; // to send username through socket without
String h=getUserInput();
// waiting
// Send the message to the server
// send public key
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
System.out.println(h);
bw.write(h);
bw.flush();
System.out.println("Message sent to the Authentication server : "+ h);
Server side:
Socket clientSocket = null;
try {
System.out.println("Server Running");
int serverPort = 8029; // the server port we are using
ServerSocket listenSocket = new ServerSocket(serverPort);
List<BlockChain> resultList = new ArrayList<BlockChain>();
while (true) {
clientSocket = listenSocket.accept();
InputStream is = clientSocket.getInputStream();
System.out.println(is);
InputStreamReader isr = new InputStreamReader(is);
System.out.println(isr);
BufferedReader br = new BufferedReader(isr);
String request = br.readLine();
System.out.println("the msg receving from client is : "+request);
PrintWriter out;
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())));
if (clientSocket != null) {
clientSocket.close();
}
}
catch (Exception e) {
e.printStackTrace();// TODO: handle exception
}
}
Someone tell me where is the problem exactly.

using a socket to print raw text

i'm working on an application to print to my local wifi printers but over 9100 port i have no response, over the 515 i have "connection refused".
the code is this:
Socket test = new Socket();
Socket sock = new Socket(ip,9100);
PrintWriter oStream = new PrintWriter(sock.getOutputStream());
oStream.printf("========================\n");
oStream.printf("PROVA STAMPA\n");
oStream.printf("HELLO SLOW SUD\n");
oStream.printf("========================"+"\n");
oStream.close();
sock.close();
and also i have try this:
Socket objSocket = new Socket();
InetSocketAddress objEndPoint = new InetSocketAddress(ip, 9100);
DataOutputStream objOutputStream;
objSocket.connect(objEndPoint, 6000);
objOutputStream = new DataOutputStream(objSocket.getOutputStream());
objOutputStream.write(("========================\nPROVA STAMPA\nHELLO SLOW SUD\n========================\n").getBytes());
objOutputStream.close();
objSocket.close();

Java Socket Client not Recieving Data

I have created my first test application implementing a socket server. I am having some issues getting the client to receive data, but the server gets data just fine. Here is the server:
ServerSocket socket = new ServerSocket(11111);
System.out.println("CREATING SERVER...");
while (true) {
Socket SERVER_WORK = socket.accept();
BufferedReader clientIN = new BufferedReader(new InputStreamReader(SERVER_WORK.getInputStream()));
PrintWriter outSend = new PrintWriter(SERVER_WORK.getOutputStream());
String ClientSTR = clientIN.readLine();
System.out.println("Client 1: " + ClientSTR);
String toClient = "Hello";
outSend.write(toClient + '\n');
}
And here is the client:
System.out.println("CONNECTING TO SERVER...");
while (true) {
Socket clientSocket = new Socket(server, 11111);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream toServere = new DataOutputStream(clientSocket.getOutputStream());
Scanner in = new Scanner(System.in);
toServere.write(in.nextLine().getBytes());
if (fromServer.ready())
System.out.println(fromServer.readLine());
clientSocket.close();
}
Everything works properly except for the client receiving data.
I found the solution: I needed a '\n' at the end of the line for the DataOutputStream/PrintWriter for the BufferedReader to work properly.

how to send TCP Requests in java

I am using Sockets to connect using TCP and I want to make different calls. e.g. Get InputValue
I have these type of different requests which I want to make from already running server.
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
String func="Get inputvalue";
byte[] tRequest = encoder.string2bytes(func);
out.write(tRequest);
out.flush();
System.out.println("write done");
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
It says it connected as just connected printout got printed. Write done print is also printed but no data is returned and the program keeps on running.
If I use telnet then this same request call returns data successfully.
So the question is how to make TCP calls in java?
Update: I solved this by:
PrintWriter toServer =
new PrintWriter(client.getOutputStream(),true);
BufferedReader fromServer =
new BufferedReader(
new InputStreamReader(client.getInputStream()));
toServer.println("Get inputvalue\r\n");
String line = "";
System.out.println("Client received: ");
while ((line = fromServer.readLine()) != null) {
System.out.println(line);
}
but the program keeps on running in the while loop and prints nothing. how to check that response is ended?

TCP Connection readline error/incorrect reading

What is happenning:
Main server -> String("isalive") => Other server
Other server -> String("alive") => Main server
Ports and stuff are configured (both servers are dedicated machines)
And code. The place where stuff seem to break is (i added debug messages....)
reader.readLine();
Main server code:
Socket clientSocket = new Socket(key, 6789);
if(clientSocket.isConnected() && !clientSocket.isClosed()){
String in;
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(isalive);
outToServer.flush();
//it wont go pass this one
in = inFromServer.readLine();
if(in.equals("alive")){
if(!Data.hosts.get(key)){
Data.hosts.put(key, true);
}
}
outToServer.close();
inFromServer.close();
clientSocket.close();
It wont go pass this one because it will stop at the other server.
Code:
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
//stuck here
rec = inFromClient.readLine();
if(rec.equals("isalive")){
outToClient.writeBytes("alive");
}
inFromClient.close();
outToClient.flush();
outToClient.close();
connectionSocket.close();
Thanks in advance.
You should not combine DataOutputStream and BufferedReader.
Consider using PrintWriter instead and specify character encodings as well (to be safe).
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
writer.println("Hello.");
writer.flush();
reader.readLine();

Categories