tes*_*est -3 java udp tcp deprecated
我的教授.给了我这个TCP/UDP的例子,他说这对他有用.但是当我去编译时,我得到一个弃用的API错误,说readLine不再使用了...
我该如何处理?
码:
import java.io.*;
import java.net.*;
public class Server{
static Socket clientSocket = null;
static ServerSocket serverSocket = null;
// This chat server can accept up to 10 clients' connections
static clientThread t[] = new clientThread[10];
public static void main(String args[]) {
// The default port
int port_number=2222;
if (args.length < 1)
{
System.out.println("Usage: java MultiThreadChatServer \n"+
"Now using port number="+port_number);
} else {
port_number=Integer.valueOf(args[0]).intValue();
}
try {
serverSocket = new ServerSocket(port_number);
}
catch (IOException e)
{System.out.println(e);}
while(true){
try {
clientSocket = serverSocket.accept();
for(int i=0; i<=9; i++){
if(t[i]==null)
{
(t[i] = new clientThread(clientSocket,t)).start();
break;
}
}
}
catch (IOException e) {
System.out.println(e);}
}
}
}
class clientThread extends Thread{
DataInputStream is = null;
PrintStream os = null;
Socket clientSocket = null;
clientThread t[];
public clientThread(Socket clientSocket, clientThread[] t){
this.clientSocket=clientSocket;
this.t=t;
}
public void run()
{
String line;
String name;
try{
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
os.println("Enter your name.");
name = is.readLine();
os.println("Hello "+name+" to our chat room.\nTo leave enter /quit in a new line");
for(int i=0; i<=9; i++)
if (t[i]!=null && t[i]!=this)
t[i].os.println("*** A new user "+name+" entered the chat room !!! ***" );
while (true) {
line = is.readLine();
if(line.startsWith("/quit")) break;
for(int i=0; i<=9; i++)
if (t[i]!=null) t[i].os.println("<"+name+"> "+line);
}
for(int i=0; i<=9; i++)
if (t[i]!=null && t[i]!=this)
t[i].os.println("*** The user "+name+" is leaving the chat room !!! ***" );
os.println("*** Bye "+name+" ***");
for(int i=0; i<=9; i++)
if (t[i]==this) t[i]=null;
is.close();
os.close();
clientSocket.close();
}
catch(IOException e){};
}
}
Run Code Online (Sandbox Code Playgroud)
Client类中也发生了同样的事情.
阅读javadoc.这就解释了为什么不推荐使用该方法以及如何替换它.
显然,当您在Javadoc中提供更改时,您需要使用您的智能.如果声明了BufferedReader,则必须导入该类,并确保代码使用它.并且您需要确保没有代码尝试使用包装的流.(在这个例子中不应该是一个问题.)
尽管已弃用,但您可以使用该方法.您只需要配置Java编译器(例如,通过IDE的编译器首选项)将弃用的方法视为警告而不是错误.(我不会在这种情况下推荐它.根据javadoc中的建议,修改代码会更好.)
你的教授应该更清楚.在JDK 1.1中,该特定方法显然首先被标记为已弃用.(或许他/她正在测试你为自己解决问题的能力!)
| 归档时间: |
|
| 查看次数: |
3387 次 |
| 最近记录: |