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

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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
关于你目前拥有的:
我首先想到的是这个循环:
while ((line = in.readLine()) != null) {
System.out.println(line);
bw.write(line+"\n");
bw.flush();
bw.close(); // <- Problem
}
Run Code Online (Sandbox Code Playgroud)
每次写一行时,您都在关闭作者。现在,作为Writer.close()状态的文件:
关闭流,首先刷新它。一旦流关闭,进一步的 write() 或 flush() 调用将导致抛出 IOException。关闭先前关闭的流没有任何效果。
你应该IOException在第一行之后的每一行都得到s 。但是,您的程序不会崩溃,因为您正在捕获异常。
其次,您使用DataInputStream从客户端读取,但使用BufferedWriter. 正如前者在其文档中所述:
数据输入流允许应用程序以独立于机器的方式从底层输入流中读取原始 Java 数据类型。应用程序使用数据输出流来写入稍后可由数据输入流读取的数据。
该类包括用于 boolean、char、int 以及您能想到的任何原始数据类型的多种方法。但是对于DataInputStream.readLine()-method,它明确指出:
已弃用。此方法不能正确地将字节转换为字符。 从 JDK 1.1 开始,读取文本行的首选方法是通过
BufferedReader.readLine()方法。
因此,对于读取字符串,您应该使用BufferedReader.
关于你还没有的:
套接字上的通信建立在“询问-回答”基础上。工作流程应该是这样的:
OutputStream)InputStream)OutputStream)InputStream)