I have a program that receives data from server and print data .How can I turn the program into a program that sends back other data after receiving data ? I tried adding datainputstream and dataoutputstream to both programs but it didn't work, it didn't give an error and it stopped working, so I deleted it back. Server :
package testSocket;
import java.net.*;
import java.io.*;
import javax.swing.JFrame;
public class server {
public static void main(String[] args) throws IOException {
JFrame jframe = new JFrame("TEST SERVER");
jframe.setVisible(true);
jframe.setSize(800, 600);
try (ServerSocket sws = new ServerSocket(13481)) {
Socket socket = sws.accept();
OutputStream outs = socket.getOutputStream();
DataOutputStream douts = new DataOutputStream(outs);
douts.writeUTF("Hello.");
douts.close();
outs.close();
} catch (Exception e) {
System.out.println("Exception : " + e);
}
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Client :
package testSocket;
import java.io.*;
import java.net.*;
public class client {
public static void main(String[] args) throws IOException {
Socket tcs = new Socket("localhost", 13481);
InputStream iss = tcs.getInputStream();
DataInputStream dis = new DataInputStream(iss);
String str = new String(dis.readUTF());
System.out.println("test " + str);
dis.close();
iss.close();
tcs.close();
}
}
Im trying to make a program that will send back a specified data to me when I send data from the server's Can you suggest something about this ?
You need to create a separate thread for Rx, Tx, and Connection operations. The reason being that sockets block the current thread and sit and wait for data. So you put the Rx, Tx, Connection, and message processing all into their own thread (or even better, a service)
Thread rxThread = new Thread(()->{
// read from DataInputStream and cache it (usually into a thread-safe collection)
});
Thread txThread = new Thread(()->{
// send messages (usually cached in some thread-safe collection)
});
Thread acceptConnections = new Thread(()->{
Socket clientConnect = serverSocket.accept();
// handle your connections here
});
It's pretty complicated. It's A lot of basic java knowledge all coming together into one application.
Research java concurrency, full duplex socket communications and possibly any implementation of an echo server you can find.
java: Single socket on read write operation. Full duplex - has a link to an implementation on github
Funny enough, oracle made an EchoServer.java tutorial... https://docs.oracle.com/javase/tutorial/networking/sockets/examples/EchoServer.java
I started making a mock-up for you, but realized how involved it was and stopped.