我正在尝试创建一个线程来简单地将文本发送到客户端。但是,如果将此代码复制到IDE,您将看到client.getOutputStream()下面有一个红色下划线。我不知道这里有什么问题。 IDE显示“未处理的异常类型IOException”。有人可以告诉我吗?
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ServerStudentThread extends Thread {
Socket client;
public ServerStudentThread(Socket x) {
client = x;
}
public void run() {
// create object to send information to client
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
out.println("Student name: ");//send text to client;
}
}
供参考,这是调用线程的代码。
import java.io.*;
import java.net.*;
import java.util.*;
public class Server2 {
public static void main(String args[]) throws Exception {
int PORT = 5555; // Open port 5555
//open socket to listen
ServerSocket server = new ServerSocket(PORT);
Socket client = null;
while (true) {
System.out.println("Waiting for client...");
// open client socket to accept connection
client = server.accept();
System.out.println(client.getInetAddress()+" contacted ");
System.out.println("Creating thread to serve request");
ServerStudentThread student = new ServerStudentThread(client);
student.start();
}
}
}
答案 0 :(得分:3)
getOutputStream()可能会抛出异常并且你没有抓住它,尝试在代码块周围放置一个try / catch(IOException e)。
public void run() {
try {
// create object to send information to client
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
out.println("Student name: ");//send text to client;
} catch (IOException e) {
throw new RuntimeException("It all went horribly wrong!", e);
}
}
答案 1 :(得分:1)
所以你需要添加一个try / catch块来处理I / O异常。
阅读Java教程中的Exceptions部分。
答案 2 :(得分:0)
来自javadoc:
public OutputStream getOutputStream()抛出IOException
IOException是一个经过检查的例外。您需要使用try
/ catch
块来处理这种可能性。
答案 3 :(得分:-1)
卡拉,
您需要将该行置于try / catch块之间或声明run以抛出IOException