0
我正在使用Java Socket開發Client-Server應用程序。我的應用程序有服務器,該服務器將偵聽端口從客戶端java讀取數據時出現連接重置錯誤
- 客戶端將連接到該端口
- 接收數據從客戶端
- 將數據發送到客戶端
部分我的代碼的
public void run() {
System.out.println("Got a client !");
try {
// Get Data From Client
int red = -1;
byte[] buffer = new byte[5 * 1024]; // a read buffer of 5KiB
byte[] redData;
StringBuilder clientData = new StringBuilder();
String redDataText;
while ((red = clientSocket.getInputStream().read(buffer)) > -1) {
/* Get Data From Client Here Code Hidden */
System.out.println("Data From Client :"
+ clientData.toString());
OutputStream out = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
String sDataToClient = "TEST DATA TO SEND IN BYTE ARRAY";
byte[] b = sDataToClient.getBytes("UTF-8");
byte[] bClientSend = new byte[b.length + 2];
bClientSend[0] = (byte) 1;
bClientSend[1] = (byte) 79;
System.arraycopy(b, 0, bClientSend, 2, b.length);
dos.write(bClientSend);
System.out.println(Arrays.toString(bClientSend));
}
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
我得到java.net.SocketException: Connection reset
後數據發送到客戶端在下面的行
while ((red = clientSocket.getInputStream().read(buffer)) > -1) {
我能看到的System.out.println(Arrays.toString(bClientSend));
數組內容然後出現錯誤
您是否關閉了服務器端的連接?查看異常的可能原因:http://stackoverflow.com/questions/62929/java-net-socketexception-connection-reset – jpe
訪問鏈接之前...是因爲在將數據發送到客戶端後我的客戶端關閉與服務器的連接因此我在'while'循環中出錯? – Shaggy
我的服務器不關閉與客戶端的連接 – Shaggy