因此,我编写了一个简单的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());
}
}
我是新来的插座和不知道我应该会看到什么。我在终端上编译了两个程序,但不知道我应该先运行哪一个程序,还是需要同时启动?
谢谢
您应该先启动服务器,以便客户端有连接的东西。在客户端中,您可以指定服务器的IP地址及其正在侦听的端口。 –
而对于ServerSocket我使用相同的端口号? – Nick
是的。你有没有试过这个?如果您看到错误,请发布。 –