[英]Java sockets, sending data to and from?
好吧,我試圖設置一個程序,我必須從套接字接收數據,然后將數據發送到套接字。 我很困惑如何讓套接字的客戶端發送特定的數據,然后讓服務器端發送特定的數據。 這是我目前擁有的,這只是我的服務器端,因為到目前為止,我真的在客戶端方面迷路了。
為了進一步評估,我想按以下所列方式進行操作,但是我無法弄清楚要編寫什么來編寫套接字的客戶端,如果有什么代碼需要在服務器端進行重寫?
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();
}
}
}
關於您目前所擁有的:
我想到的第一件事是這個循環:
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
寫出。 如文檔中以前所述:
數據輸入流允許應用程序以與機器無關的方式從基礎輸入流中讀取原始Java數據類型 。 應用程序使用數據輸出流來寫入數據,以后可以由數據輸入流讀取。
該類包括用於boolean,char,int的多種方法,無論您想到什么原始數據類型。 但是對於DataInputStream.readLine()
方法 ,它明確指出:
不推薦使用 。 此方法不能正確將字節轉換為字符。 從JDK 1.1開始, 讀取文本行的首選方法是通過
BufferedReader.readLine()
方法。
因此,對於讀取字符串,應使用BufferedReader
。
關於您還沒有的東西:
套接字上的通信基於“詢問-應答”建立。 工作流程應如下所示:
OutputStream
) InputStream
) OutputStream
) InputStream
) 除了您的代碼,我沒有發現任何明顯錯誤的地方:
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.