Java Socket を使用してクライアント サーバー アプリを開発しています。私のアプリケーションには、ポートでリッスンするサーバーがあります
- クライアントはそのポートに接続します
- クライアントからデータを受信
- クライアントにデータを送信
私のコードの一部
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));
エラーが発生した場合の配列の内容を確認できます