Java Network Programmingを学習しようとしていますが、いくつかのロードブロッキングが発生しています。私はサーバーとクライアントをすでに作成していますが、それらを接続しようとするたびに、すぐに接続がクローズされるというエラーが表示されます。その後、私はそれを編集しようとしましたが、接続が拒否されました。これを機に、私は非常に単純なサーバー上でソケットとServerSocketsの基本をテストすることにしました。そう、私はこの2つのクラスを作ってみた:Java SocketServerはSocketクライアントからの入力を受け付けていますが、SocketクライアントはSocketServerからの入力を受け付けていません
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
public class SimpleServer {
public static void main(String[] args) throws Exception {
System.out.println("hey there");
ServerSocket server = new ServerSocket(50010);
Socket socket = server.accept();
System.out.println("Connection at " + socket);
InputStream in = socket.getInputStream();
int c = 0;
while ((c = in.read()) != -1) {
System.out.print((char)c);
}
OutputStream out = socket.getOutputStream();
for (byte b : (new String("Thanks for connecting!")).getBytes()) {
out.write(b);
out.flush();
}
in.close();
out.close();
socket.close();
server.close();
}
}
と
import java.net.Socket;
import java.io.*;
public class SimpleClient {
public static void main(String[] args) throws Exception {
System.out.println("Attempting connection");
Socket s = new Socket("130.49.89.208", 50010);
System.out.println("Cool");
OutputStream out = s.getOutputStream();
for (byte b : (new String("Hey server\r\nThis message is from the client\r\nEnd of message\r\n")).getBytes()) {
out.write(b);
out.flush();
}
InputStream in = s.getInputStream();
int c = 0;
System.out.println("this message will print");
while ((c = in.read()) != -1) {
System.out.print((char)c);
System.out.println("this does not print");
}
out.close();
in.close();
s.close();
}
}
サーバは、クライアントのメッセージが完全に罰金受けるが、それは、サーバーのターンのとき、クライアントへの書き込みにすべてがブロックされます。
Serverの出力:
-java SimpleServer
----hey there
----Connection at Socket[addr=/130.49.89.208,port=59136,localport=50010]
----Hey server
----This message is from the client
----End of message
クライアントの出力:
-java SimpleClient
----Attempting connection
----Cool
----this message will print
クライアントとサーバーの両方ことができます場合は、大学のインターネット接続とイーサネット接続に私のラップトップ上で実行します。 Javadocによる