好吧,我正在尝试设置一个程序,我必须从套接字接收数据,并将数据发送到套接字。我很难理解如何让套接字的客户端发送特定数据,然后让服务器端发送特定数据。这是我目前拥有的,它只是我的服务器端,因为到目前为止我真的迷失在客户端部分。
为了进一步评估,我想做如下所列,但我不知道要研究什么来编写套接字的客户端,如果有任何代码我需要在服务器端重写?
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();
}
}
}