嘿伙计们,我正在尝试编写一个简单的套接字程序,该程序基本上从客户端发送“Hello”消息,然后服务器获取并打印出来。
我正在尝试遵循本指南: http ://www.javaworld.com/jw-12-1996/jw-12-sockets.html?page=4
但是,当我尝试使用端口号实例化 serverSocket 时,会导致语法错误,建议删除参数或为该方法创建新的构造函数。当我尝试使用它时,它也无法识别 accept() 方法。有谁知道为什么会这样?
这是我的客户代码:
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());
}
}
以下是实际截图。
错误1:http: //i.imgur.com/8JIOd.png 错误2: http : //i.imgur.com/7uCow.png