そこで、クライアントからサーバープログラムにメッセージを送信する単純なソケットプログラムを作成し、これをテストするための適切な手順を知りたいと思いました。クライアントマシンとサーバーマシンの両方がUbuntu12.04で実行されており、両方にリモート接続しています。
クライアントソケット(testSocket)をインスタンス化するときのクライアントコードには、そのIPアドレスとポート番号またはサーバーのIPアドレスとポート番号を使用しますか?
クライアントのコードは次のとおりです。
public static void main(String[] args) throws UnknownHostException, IOException
{
Socket testSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
try
{
testSocket = new Socket("192.168.0.104", 5932);
os = new DataOutputStream(testSocket.getOutputStream());
is = new DataInputStream(testSocket.getInputStream());
}
catch (UnknownHostException e)
{
System.err.println("Couldn't find Host");
}
catch (IOException e)
{
System.err.println("Couldn't get I/O connection");
}
if (testSocket != null && os != null && is != null)
{
try
{
os.writeBytes("Hello Server!\n");
os.close();
is.close();
testSocket.close();
}
catch (UnknownHostException e)
{
System.err.println("Host not found");
}
catch (IOException e)
{
System.err.println("I/O Error");
}
}
}
サーバーのコードは次のとおりです。
public static void main(String[] args)
{
String line = new String() ;
try
{
ServerSocket echoServer = new ServerSocket(5932);
Socket clientSocket = echoServer.accept();
DataInputStream is = new DataInputStream(clientSocket.getInputStream());
PrintStream os = new PrintStream(clientSocket.getOutputStream());
while (true)
{
line = is.readLine();
os.println(line);
}
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
私はSocketsを初めて使用しますが、何が表示されるのかわかりません。両方のプログラムをターミナルで正常にコンパイルしましたが、どちらを最初に実行する必要があるのか、または同時に開始する必要があるのかわかりません。
ありがとう