我尝试创建一个应该发送和接收文本消息的程序(UTF-8字符串)。
对于此错误,我正在服务器端
服务器的命令行参数类似于
java DirectMessengerServer -l 6021
此屏幕截图的问题是“Try block beginning”未打印出来(这是代码中稍后会忽略的行)。
DirectMessengerServer.java代码:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerServer
{
public static void main(String args[]) throws IOException
{
Thread Server = new Thread ()
{
public void run ()
{
System.out.println("Server thread is now running");
ServerSocket server_socket = null;
Socket client_socket;
String message1;
for(int i = 0; i < args.length; i++)
{
if(args[0] == "-l")
{
try
{
System.out.println("Try block begins..");
int port_number1= Integer.valueOf(args[1]);
ServerSocket listener = new ServerSocket(port_number1);
System.out.println("Listening for connections..");
Socket socket = listener.accept();
client_socket= server_socket.accept();
BufferedReader reader= new BufferedReader(new InputStreamReader(client_socket.getInputStream(), "UTF8"));
PrintWriter output= new PrintWriter( client_socket.getOutputStream(), true );
String input_line= reader.readLine();
System.out.println( "Received from client: " );
System.out.println( input_line );
output.println( input_line );
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
//server.close();
}
}
}
};
Server.start();
}
}
我的问题是为什么程序在没有执行try块的情况下停止和/或为什么“Try block started”没有被执行?
答案 0 :(得分:1)
两个评论:
arg[0]
,请确保在端口号参数"-l".equals(arg[0])
代替args[0] == "-l"
,因为这是Java检查两个字符串是否具有相同内容的正确方法