I have created a simple server and client in java that sends and receives messages from one another. At the moment I have the port number hard coded into the code but i would like to change that to user input from the command line. In the code below I am using args[0] for the port number but when I compile it fails, can anyone help? I am new to both java and sockets so sorry if this is a trivial question
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 );
}
}
}
}
}
This is the error that is coming up
SimpleServer.java:14: error: no suitable constructor found for ServerSocket(String)
ServerSocket Server = new ServerSocket (args[0]);
ServerSocket Server = new ServerSocket (Integer.parseInt(args[0]));
args[0]
是string
,需要在int
进行解析
您必须使用以下方法将arg[0] (String)
为int: Integer.parseInt(arg[0])
ServerSocket没有带有ServerSocket(String)
构造函数
The constructor parameter is of type int, while the arguments given to main are of type String. Solution is simply to use Integer.valueOf(args[0]) to parse the argument into an integer. You might want to add more robustness checks, etc - but for a quick fix this should work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.