こんにちは、ソケットプログラミングを介してチャットアプリケーションを作成しようとしています。
ただし、クライアント側でもサーバー側でもメッセージを送信したり受信したりできません。System.out.println ステートメントのみが出力として表示されます。同じコードを配置しています。
サーバ:
import java.net.*;
import java.io.*;
class MyServer
{
public static void main(String arr[])
{
try
{
ServerSocket server=new ServerSocket(2500);//the server is listening to at this port
System.out.println("Server is ready , waiting for a connection request...");
/*Now the accept() method blocks while it is waiting for a client Socket connection.When a client finally tries to connect, the method returns a plain old Socket (on a
diffrent port) that knows how to communicate with the client(i.e. knwos the client IP address and port number).The SOcket is on a different port than the ServerSocket,
so that the ServerSocket can go back to waiting for other clients.*/
Socket sock=server.accept();
System.out.println("Request received , connection completed...");
Thread.sleep(10000);
System.out.println("Waiitng for message...");
BufferedReader b=new BufferedReader(new InputStreamReader(sock.getInputStream()));
String msg=b.readLine();
System.out.println("Received message "+msg);
Thread.sleep(10000);
System.out.println("Sending acknowledgement");
PrintStream out=new PrintStream(sock.getOutputStream());
Thread.sleep(30000);
out.println("Hello client, your test message is received");
System.out.println("Ack sent, clsoing connection");
Thread.sleep(50000);
server.close();
sock.close();
System.out.println("Connection closed");
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
クライアント:
import java.net.*;
import java.io.*;
class MyClient
{
public static void main(String arr[])
{
try
{
System.out.println("Client ready , sending request...");
Thread.sleep(10000);
Socket socket=new Socket("localhost",2500);;
Thread.sleep(10000);
System.out.println("Connection completed , sending message");
PrintStream out=new PrintStream(socket.getOutputStream());
Thread.sleep(30000);
out.println("Hello server, its a test message");
BufferedReader b=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg=b.readLine();
System.out.println("Ack message "+msg);
Thread.sleep(10000);
System.out.println("clsoing connection");
Thread.sleep(50000);
socket.close();
System.out.println("Connection closed");
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
出力: クライアント上:
D:\java>java MyClient
Client ready , sending request...
Connection completed , sending message
Ack message Hello client, your test message
clsoing connection
Connection closed
サーバー上:
D:\java>java MyServer
Server is ready , waiting for a connection request...
Request received , connection completed...
Waiitng for message...
Received message Hello server, its a test message
Sending acknowledgement
Ack sent, clsoing connection
Connection closed
キーボードから入力できません