gpt4 book ai didi

Java 套接字命令行参数

转载 作者:行者123 更新时间:2023-11-30 06:15:26 25 4
gpt4 key购买 nike

我用 java 创建了一个简单的服务器和客户端,它们可以相互发送和接收消息。目前我已将端口号硬编码到代码中,但我想将其更改为用户从命令行输入的内容。在下面的代码中,我使用 args[0] 作为端口号,但是当我编译它失败时,有人可以帮忙吗?我是 java 和套接字的新手,如果这是一个微不足道的问题,我很抱歉

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]);

最佳答案

ServerSocket Server = new ServerSocket (Integer.parseInt(args[0]));

args[0]string,需要解析成int

关于Java 套接字命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28810825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com