John
John

Reputation: 4038

Help me to fix a bug in this thread example

I am trying to create a thread to simply send the text to client. However, if you copy this code to IDE, you will see that there is a red underline under client.getOutputStream(). I do not know what is wrong here. The IDE says "Unhandled exception type IOException". Could anybody tell me?

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;
  }
}

For reference, here is the code that calls the thread.

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();
    }
  }
}

Upvotes: 2

Views: 1211

Answers (4)

rajeshnair
rajeshnair

Reputation: 1673

Kalla,

You need to either put the line in between try/catch block or declare run to throw IOException

Upvotes: -1

camickr
camickr

Reputation: 324207

So you need to add a try/catch block to handle the I/O exception.

Read the section on Exceptions from the Java tutorial.

Upvotes: 1

Tim Bender
Tim Bender

Reputation: 20442

From the javadoc:

public OutputStream getOutputStream() throws IOException

IOException is a checked exception. You need to use a try/catch block to handle that possibility.

Upvotes: 0

Tom
Tom

Reputation: 44881

It's probably that getOutputStream() can throw an exception and you're not catching it, try putting a try / catch (IOException e) around the block of code.

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

Upvotes: 3

Related Questions