因此,我编写了一个简单的 Socket 程序,将消息从客户端发送到服务器程序,并想知道进行测试的正确程序是什么?我的客户端和服务器机器都在 Ubuntu 12.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 的新手,不确定我应该看到什么。我在终端很好地编译了两个程序,但不确定我应该先运行哪个程序还是需要同时启动它们?
谢谢