好吧,我正在尝试设置一个程序,我必须从套接字接收数据,并将数据发送到套接字。我很难理解如何让套接字的客户端发送特定数据,然后让服务器端发送特定数据。这是我现在拥有的,它只是我的服务器端,因为我现在真的迷失在客户端部分。
为了进一步评估,我想按照下面列出的那样做,但是我无法弄清楚要编写什么来编写套接字的客户端,如果有任何代码我需要重写服务器端?
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();
}
}
}
答案 0 :(得分:4)
关于您目前拥有的内容:
我眼中的第一件事就是这个循环:
while ((line = in.readLine()) != null) {
System.out.println(line);
bw.write(line+"\n");
bw.flush();
bw.close(); // <- Problem
}
每次写一行时你都会关闭作家。现在,正如Writer.close()
所述的文档:
关闭流,先冲洗它。 一旦流已经 关闭,进一步的write()或flush()调用将导致 抛出IOException。关闭以前关闭的流没有 效果。
在第一行之后,您应该为每一行获得IOException
个。然而,您的程序不会崩溃,因为您正在捕获异常。
其次,您使用DataInputStream
从客户端读取,但使用BufferedWriter
写出来。正如前者在it's documentation中陈述的那样:
数据输入流允许应用程序读取原始Java数据类型 来自基础输入流,与机器无关。一个 应用程序使用数据输出流来写入以后可以使用的数据 由数据输入流读取。
该类包括boolean,char,int的多种方法,您可以想到的任何原始数据类型。但对于DataInputStream.readLine()
-method,它明确指出:
<强>已过时即可。 此方法无法将字节正确转换为字符。 从JDK 1.1开始,读取文本行的首选方法是通过
BufferedReader.readLine()
方法。
因此,要阅读字符串,您应该使用BufferedReader
。
关于您还没有的内容:
套接字通信建立在“问答”基础上。工作流程应该是这样的:
OutputStream
)InputStream
)OutputStream
)InputStream
)答案 1 :(得分:0)
除了以下代码之外,我没有看到任何明显错误:
DataInputStream in = new DataInputStream(clientSock.getInputStream());
while ((line = in.readLine()) != null) {
不推荐使用 DataInputStream.getLine()
- 您应该只使用BufferedReader.getLine()
:
使用DataInputStream类读取行的程序可以通过替换表单的代码转换为使用BufferedReader类:
DataInputStream d = new DataInputStream(in);
使用:
BufferedReader d = new BufferedReader(new InputStreamReader(in));