我在java中创建了一个简单的服务器和客户端,用于发送和接收彼此的消息。目前我将端口号硬编码到代码中,但我想将其从命令行更改为用户输入。在下面的代码中我使用args [0]作为端口号但是当我编译它失败时,任何人都可以帮忙吗?我是java和socket的新手,如果这是一个微不足道的问题,那就很抱歉
import java.io.*;
import java.net.*;
class SimpleServer
{
public static void main(String args[]) throws Exception
{
//declaring string variables
String fromclient;
String toclient;
//new socket object, listening on port 3000
ServerSocket Server = new ServerSocket (args[0]);
//prints when started and no client connected
System.out.println ("TCPServer Waiting for client on port 3000");
//infinate loop
while(true)
{
//listens for connection
Socket connected = Server.accept();
//prints clients adddress and port
System.out.println( " THE CLIENT"+" "+ connected.getInetAddress() +":"+connected.getPort()+" IS CONNECTED ");
//reads in message form user
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
//reads in message from clinet
BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connected.getInputStream()));
//prints message to client
PrintWriter outToClient = new PrintWriter(connected.getOutputStream(),true);
//infinate loop
while ( true )
{
//printing instructions for killing connection
System.out.println("SEND(Type Q or q to Quit):");
//reading in user input
toclient = inFromUser.readLine();
//if user enters q or Q kill connection
if ( toclient.equals ("q") || toclient.equals("Q") )
{
outToClient.println(toclient);
connected.close();
break;
}
else
{
outToClient.println(toclient);
}
//reading from client
fromclient = inFromClient.readLine();
//if user enter q or Q kill connection
if ( fromclient.equals("q") || fromclient.equals("Q") )
{
connected.close();
break;
}
//printing out the message from client
else
{
System.out.println( "RECIEVED:" + fromclient );
}
}
}
}
}
这是即将出现的错误
SimpleServer.java:14: error: no suitable constructor found for ServerSocket(String)
ServerSocket Server = new ServerSocket (args[0]);
答案 0 :(得分:2)
ServerSocket Server = new ServerSocket (Integer.parseInt(args[0]));
args[0]
为string
,需要在int
中解析
答案 1 :(得分:2)
您必须使用arg[0] (String)
将Integer.parseInt(arg[0])
转换为int
ServerSocket没有ServerSocket(String)
答案 2 :(得分:1)
构造函数参数的类型为int,而赋予main的参数的类型为String。 解决方案只是使用Integer.valueOf(args [0])将参数解析为整数。 您可能希望添加更多健壮性检查等 - 但是为了快速解决这个问题,这应该可行。