Communication between Java programs - java

I'm trying to learn how to do deal with networks in Java 8, and I'm trying to make a client program communicate with a server one. The client is asked a string, which is sent to the server, and the server sends it back in upper characters.
I can't get my server part to work, it simply won't write anything except the fact that the connection is made. Could someone explain what's wrong with my code ?
Server :
public static void main(String[] args) throws IOException {
int listenPort = 9000;
ServerSocket listenSocket = new ServerSocket(listenPort);
Socket socket = listenSocket.accept();
System.out.println("Connexion réussie !");
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream));
DataOutputStream output = new DataOutputStream(outputStream);
String line = null;
System.out.println("test : " + buffer.readLine());
while((line = buffer.readLine()) != null) {
System.out.println("Message reçu : " + line);
System.out.println("Message envoyé : " + line.toUpperCase());
output.writeUTF(line.toUpperCase());
if(line.equals("stop")) {
socket.close();
listenSocket.close();
}
}
}
Client side :
public static void main(String[] args) throws IOException, UnknownHostException {
Socket socket = new Socket("127.0.0.1", 9000);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
DataInputStream input = new DataInputStream(inputStream);
DataOutputStream output = new DataOutputStream(outputStream);
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line = buffer.readLine()) != null) {
System.out.println("Message envoyé : " + line);
output.writeChars(line);
System.out.println("Message reçu : " + input.readUTF());
if(line.equals("stop")) {
break;
}
}
socket.close();
}

Inside your client method, you call output.writeChars(line) inside the while loop, this means that you send something to the server after the server send something to you.
Change your client code as follows:
String line = "What a wonderful line";
System.out.println("Message envoyé : " + line);
output.writeChars(line);
while((line = buffer.readLine()) != null) {
System.out.println("Message reçu : " + input.readUTF());
}

Related

Why is my program running twice on my Server?

I am writing tcp client-server program. When the client types "Hello" the server returns a list of files and directories of his current directory. When the client types "FileDownload " it downloads the selected file from the server.
When I type "Hello" it works fine, but when I type "FileDownload ", on the server side it runs twice the else if(received.contains("FileDownload")) block. Because of this the server is sending twice the data which is causing other issues on the client side.
Here is the server code:
public static void main(String[] args) throws IOException {
ServerSocket servSock = new ServerSocket(1333);
String received="";
String[] s = null;
File[] f1;
int i=0;
File f=new File(System.getProperty("user.dir"));
f1=f.listFiles();
for(File f2:f1) {
if(f2.isDirectory())
System.out.println(f2.getName() + "\t<DIR>\t" + i);
if(f2.isFile())
System.out.println(f2.getName() + "\t<FILE>\t" + i);
i++;
}
while (true) {
Socket client = servSock.accept();
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
PrintWriter pw = new PrintWriter(out, true);
s=f.list();
while(true) {
received = reader.readLine();
if(received.equals("END")) break;
if(received.equals("Hello")) {
System.out.println("Hello-Start");
int length=f1.length;
pw.println(length);
i=0;
for(File f2:f1) {
if(f2.isDirectory())
pw.println(f2.getName() + "\t<DIR>\t" + i);
if(f2.isFile())
pw.println(f2.getName() + "\t<FILE>\t" + i);
i++;
}
pw.println("Options: " + "\tFileDownload <FID>" + "\tFileUpload <name>" + "\tChangeFolder <name>");
System.out.println("Hello-End");
}
else if(received.contains("FileDownload")) {
System.out.println("FileDownload-Start");
int j=-1;
try {
j=Integer.parseInt(received.substring(13).trim());
}catch(NumberFormatException e) {
System.err.println("error: " + e);
}
if(j>0 && j<s.length) {
FileInputStream fi=new FileInputStream(s[j]);
byte[] b=new byte[1024];
System.out.println("file: "+s[j]);
pw.println(s[j]);
fi.read(b,0,b.length);
out.write(b,0,b.length);
System.out.println("FileDownload-End");
}
}
Here is the client code:
public static void main(String[] args) throws IOException {
if ((args.length != 2))
throw new IllegalArgumentException("Parameter(s): <Server> <Port>");
Socket socket = new Socket(args[0], Integer.parseInt(args[1]));
Scanner sc = new Scanner(System.in);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
PrintWriter pw = new PrintWriter(out, true);
while(true) {
String msg="", received="";
String length;
msg = sc.nextLine();
pw.println(msg);
if(msg.equals("END")) break;
if(poraka.equals("Hello")) {
System.out.println();
length = reader.readLine();
for(int i=0;i<Integer.parseInt(length);i++) {
received = reader.readLine();
System.out.println(received);
}
System.out.println("\n"+reader.readLine());
}
else if(msg.contains("FileDownload")) {
System.out.println("FileDownload-Start");
pw.println(msg);
byte[] b=new byte[1024];
File file=new File(reader.readLine().trim());
System.out.println(file.getName().trim());
FileOutputStream fo=new FileOutputStream("D:\\Eclipse WorkSpace\\proekt\\src\\client\\"+file.getName().trim());
System.out.println("file: "+file.getName().trim());
in.read(b,0,b.length);
fo.write(b,0,b.length);
System.out.println("FileDownload-End");
}
I could not find what's causing this issue, so any help possible would be very highly appreciated!
It is because your client requests the data twice:
msg = sc.nextLine();
pw.println(msg); // <-- this is the first time
and then later
else if(msg.contains("FileDownload")) {
System.out.println("FileDownload-Start");
pw.println(msg); // <-- this is the second time

Socket java transfer a bit string to the server. StringBuilder Transfer [duplicate]

This question already has answers here:
fsockopen equivalent in JSP
(3 answers)
Closed 4 years ago.
I have a task. By socket, pass the variable output.
String hex = "1040014116";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
String str = hex.substring(i, i+2);
output.append((char)Integer.parseInt(str, 16));
}
System.out.println(output);
output has the form "0x10.."
There is a web server he needs to transfer this data and in return receive others.
int serverPort = 2003;
String address = "xx.xx.xx.xx";
try {
InetAddress ipAddress = InetAddress.getByName(address);
System.out.println(" IP address " + address + " and port " + serverPort);
Socket socket = new Socket(ipAddress, serverPort);
System.out.println("Socket ready");
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = null;
System.out.println("Введите данные и нажмите 'Ввод'");
System.out.println();
while (true) {
line = reader.readLine();
System.out.println("Отправка на сервер");
out.writeUTF(line);// отправка текста
System.out.println("Отправка: : " + line);
out.flush(); // конец передачи
line = in.readUTF(); // возврат текста от сервера
System.out.println("Сервер: : " + line);
System.out.println("Введите новую строку");
System.out.println();
}
} catch (Exception x) {
x.printStackTrace();
}
}
How to pass a bit string and get a bit string from the server in response.
U need to code on both client and server side
SERVER code
ServerSocket sskt=new ServerSocket(port);
Socket =sskt.accept()
InputStream is=skt.getInputStream();
OutputStream os=skt.getOutputStream();
ClIENT code
Socket skt=new Socket(server_ip,port);
Use same inputstream and outputstream to read and write once the connection has been established
Hope this helps

Why server created using java socket doesn't not print data send from client (it dislays if client terminate)?

In example below I created one server which will only print whatever client is writing in a socket. But I am not getting output as client enter data. If client terminate then I can see all the data client inserted in outputstream. I am taking input from console at client and then write that data to server socket.
Server code:
public class server {
public static void main(String[] args) throws Exception {
System.out.println("waiting");
ServerSocket s = new ServerSocket(9999);
Socket stemp = s.accept();
System.out.println("read comp");
InputStream is = stemp.getInputStream();
InputStreamReader ir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(ir);
while(true)
{
String str = br.readLine();
if(str!=null)
{
System.out.println(str);
}
if(str.contains("exit"))
{
break;
}
}
stemp.close();
ir.close();
is.close();
br.close();
}
}
Client code:
public class client {
public static void main(String[] args) throws Exception {
String ip ="127.0.0.1";
int port = 9999;
Socket s1 = new Socket(ip, port);
OutputStream os = s1.getOutputStream();
OutputStreamWriter ow = new OutputStreamWriter(os);
BufferedWriter pw = new BufferedWriter(ow);
pw.write("I am ready");
Scanner s = new Scanner(System.in);
String str = s.nextLine();
System.out.println(str);
while(!str.contains("exit"))
{
pw.write(str);
pw.flush();
str = s.nextLine();
}
pw.close();
os.close();
ow.close();
s1.close();
}
}
In server, br.readLine(); is used, waiting for end-of-line.
In client, you have to send the eol in pw.write( str + '\n' );.

Telnet test is OK, but my java socket client is not working

My partner system services socket server. They don't share the client module, only test sample data.
First, I tested using telnet program and it's successful.
this image link is the test using telnet program.
But my Java socket client can't receive message from socket server.
this image link is result of my socket program.
Would you help me?
Thanks.
public static void main(String[] args) {
System.out.println("file.encoding: " + System.getProperty("file.encoding"));
try {
Socket socket;
final String HOST = "xx.xx.xx.xxx"; // partner test server
final int PORT = 8994;
try {
socket = new Socket(HOST, PORT);
} catch (IOException ioe) {
System.out.println(">>>");
System.out.println(ioe.getMessage());
System.out.println(">>>");
throw ioe;
}
System.out.println("sending data:");
OutputStream os = socket.getOutputStream();
byte[] b = "xxxx52017082410332310000000020321 ONL00000 080081COP0045 3xxxxxxxxxxxxxxx/jOsBUe5I11C2mtP0j5tPSww==20170824103323 ".getBytes();
for (int i = 0; i < b.length; i++) {
os.write(b[i]);
}
os.flush();
socket.shutdownOutput();
System.out.println(new String(b) + "[END]");
System.out.println("receiving data");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
socket.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
I found the solution.
The sever socket program sent byte data, not string line.
Please find below my source code.
Thanks everyone.
socket = new Socket(ip, port);
System.out.println("SEND DATA[" +msg.length() + "] [" + msg + "]");
oout = new BufferedOutputStream(socket.getOutputStream());
iin = new BufferedInputStream(socket.getInputStream());
oout.write(msg.getBytes());
oout.flush();
byte[] buffer = new byte[1156];
System.out.println("RECV DATA");
iin.read(buffer);
System.out.println("RECV DATA [" + new String(buffer) +"]");

Java two- way socket connection (server/ client)

what I'm trying to do is to send some JSON from an Android phone to a Java server, which works fine. The Android/ client side looks like this:
Socket s = new Socket("192.168.0.36", 12390);
s.setSoTimeout(1500);
JSONObject json = new JSONObject();
json.put("emergency", false);
json.put("imei", imei);
json.put("lat", l.getLatitude());
json.put("lon", l.getLongitude());
json.put("acc", l.getAccuracy());
json.put("time", l.getTime());
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
out.write(json.toString());
out.flush();
s.close();
The server side is this:
try {
s = new ServerSocket(port);
}
catch (IOException e) {
System.out.println("Could not listen on port: " + port);
System.exit(-1);
}
Socket c = null;
while (true) {
try {
c = s.accept();
} catch (IOException e) {
System.out.println("Accept failed: " + port);
System.exit(-1);
}
try {
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine = null;
String result = "";
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
System.out.println(result);
As I said, all of that works. Now I want to send a message back from the server to the client after it received the message from the client.
I extended the code like this, Android/ client side:
Socket s = new Socket("192.168.0.36", 12390);
s.setSoTimeout(1500);
JSONObject json = new JSONObject();
json.put("emergency", false);
json.put("imei", imei);
json.put("lat", l.getLatitude());
json.put("lon", l.getLongitude());
json.put("acc", l.getAccuracy());
json.put("time", l.getTime());
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
out.write(json.toString());
out.flush();
String inputLine = null;
String result = "";
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
while ((inputLine = in.readLine()) != null) {
Log.d(TAG, in.readLine());
result = result.concat(inputLine);
}
And the server side:
try {
s = new ServerSocket(port);
}
catch (IOException e) {
System.out.println("Could not listen on port: " + port);
System.exit(-1);
}
Socket c = null;
while (true) {
try {
c = s.accept();
} catch (IOException e) {
System.out.println("Accept failed: " + port);
System.exit(-1);
}
try {
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine = null;
String result = "";
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
System.out.println(result);
PrintWriter out = new PrintWriter(c.getOutputStream());
out.write("Hello phone");
out.flush();
out.close();
On the client side, nothing ever comes in, it hangs on
while ((inputLine = in.readLine()) != null) {
Log.d(TAG, in.readLine());
result = result.concat(inputLine);
}
until the socket times out (never enters the loop). I thought it might be a timing problem, for example the server sending out its reply too early and therefore the client never receiving anything, but i tried to put the out.write("Hello phone"); pretty much anywhere in the code, always the same result. Can it have to do with the socket being obtained from ServerSocket and not being able to send out data? What am I missing here, this is bugging me all day ...
Edit: After Nikolais answer, I tried this (client):
out.write(json.toString());
out.newLine();
out.write("###");
out.flush();
String inputLine = null;
String result = "";
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("###")) {
break;
}
Log.d(TAG, in.readLine());
result = result.concat(inputLine);
}
s.close();
and server:
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
if (inputLine.contains("###")) {
System.out.println("received ###");
out.println("Hello phone");
out.println("###");
out.flush();
break;
}
}
The idea was to send out the message from the server before the client closes the socket. Still doesnt work ... any hints?
On the server side you never get to sending your "Hello phone". Not until client closes the socket, but at that point it's useless. This is because in.readLine() blocks until either data is available or EOF, i.e. socket closed.
You need a way to get out of the reading loop - invent (or adopt) some application-level protocol that would tell you that a whole message is received. Common options are fixed length messages, length prefix, delimited, etc.

Categories

Resources