Alright, I’m trying to set a program I have to receive data from a socket, and send data to a socket. I’m stumped on how to get the client side of the socket to send specific data, then have the server side send specific data. Here’s what I currently have, it’s only my server-side because I’m really lost on the client part as of now.
To further evaluate, I would like to do as listed in the following, yet I can’t figure out what to research to write the client-side of the socket, and if there was any code I would need to rewrite in the server side?

package sockets;
import java.net.*;
import java.io.*;
public class SocketMain {
private int port = 0;
public ServerSocket socket;
public Socket clientSock;
public SocketMain() {
init();
}
public static void main(String[] args) {
new SocketMain();
}
private void init() {
try {
socket = new ServerSocket(port);
System.out.println("Server started, bound to port: "+port);
clientSock = socket.accept();
File directory = new File("./Storage/");
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory + "/Store.dat");
if (!file.exists()) {
file.createNewFile();
}
DataInputStream in = new DataInputStream(clientSock.getInputStream());
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
bw.write(line+"\n");
bw.flush();
bw.close();
}
socket.close();
clientSock.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
About what you currently have:
The first thing that jumped in my eye was this loop:
You’re closing the writer every time you write a line. Now, as the documentation of
Writer.close()states:You should be getting
IOExceptions for every line after the first one. You program will however not crash, since you’re catching the exceptions.Second, you use
DataInputStreamto read from your client, but write out using aBufferedWriter. As the former states in it’s documentation:The class includes multiple methods for boolean, char, int, whatever primitive data-type you can think of. But for the
DataInputStream.readLine()-method, it clearly states:So, for reading strings, you should use a
BufferedReader.About what you don’t yet have:
The communication over sockets is established on a “ask-answer” base. The workflow should be something like this:
OutputStream)InputStream)OutputStream)InputStream)