多线程Java服务器,套接字异常错误

时间:2019-01-07 20:18:14

标签: java multithreading server

为分配设置多线程服务器。似乎套接字输出流无法识别源-至少这是我从返回的错误中收集的信息。

当我在'RequestHandlerThread'Runnable类上调用run()方法时,一切都很好。据我了解,这不是多线程。当我实例化一个新线程并将其传递给我的“ RequestHandlerThread”作为可运行线程并尝试启动()线程时,我得到以下错误:

java.net.SocketException: Socket is closed
    at java.net.Socket.getOutputStream(Unknown Source)
    at RequestHandlerThread.run(RequestHandlerThread.java:25)
    at java.lang.Thread.run(Unknown Source)

Basically I think I have a misconception of threads. 

//CHATSERVER CODE

import java.net.*;
import java.io.*;
import java.util.*;



public class ChatServer3 {
    public static void main(String[] args) throws IOException {

        if (args.length != 1) {
            System.err.println("Usage: java EchoServer <port number>");
            System.exit(1);
        }

        int portNumber = Integer.parseInt(args[0]);
        ServerSocket serverSocket = new ServerSocket(portNumber);
        System.out.println("Server3 is up and running on port : " + portNumber);

        while(true) {

            try (       
                Socket clientSocket = serverSocket.accept();    


            ) {
                System.out.println("Connection to Server3 has been established");
                new Thread(new RequestHandlerThread(clientSocket)).start();

                System.out.println("this");
            } catch (IOException e) {
                System.out.println("Exception caught when trying to listen on port "
                    + portNumber + " or listening for a connection");
                System.out.println(e.getMessage());

            }
        }

    }
}

// REQUESTHANDLER THREAD CODE

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class RequestHandlerThread implements Runnable {

    Socket socket;
    PrintStream out;
    Scanner in;

    public RequestHandlerThread(Socket socket)  {
        this.socket = socket;

    }

    @Override
    public void run() {

        String inputLine;
        try {
            out = new PrintStream(socket.getOutputStream());                   
            in = new Scanner(new InputStreamReader(socket.getInputStream()));   
            while ((inputLine = in.nextLine()) != null) {
                out.println("Server3:"+inputLine);
            }
            out.close();
            in.close();
        } catch (IOException e) {

//***************************************************************
            //THIS IS WHERE THE Socket EXception error is Generated
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}


//CHAT CLIENT CODE

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ChatClient {
    public static void main(String[] args) throws IOException {

        if (args.length != 2) {
            System.err.println(
                "Usage: java EchoClient <host name> <port number>");
            System.exit(1);
        }

        String hostName = args[0];
        int portNumber = Integer.parseInt(args[1]);
        Socket echoSocket = new Socket(hostName, portNumber);
        System.out.println("Connection to server :" + hostName + " on port : " +portNumber );
        try (

            PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
            BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in))
        ) {
            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                if(userInput.equals(".quit")) {
                    System.out.println("Connection terminated by CLIENT");
                    break;
                }
                out.println(userInput);

                System.out.println( in.readLine());
            }
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                hostName);
            System.exit(1);
        } 
    }
}

我希望可以同时创建和运行线程,以便可以将多个客户端同时连接到服务器。但是我无法正确地“启动”线程

1 个答案:

答案 0 :(得分:0)

LinearLayout传递给启动的线程,但是主循环使用try-with-resources将关闭<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:orientation="vertical"> <android.support.v4.widget.DrawerLayout android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:fitsSystemWindows="true" tools:openDrawer="start"> <include layout="@layout/app_bar_wallpaper_full" android:layout_width="match_parent" android:layout_height="match_parent"/> <android.support.design.widget.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="true" app:headerLayout="@layout/nav_header_wallpaper_full" app:menu="@menu/activity_wallpaper_full_drawer"/> </android.support.v4.widget.DrawerLayout> <com.google.android.gms.ads.AdView android:id="@+id/adView" android:layout_width="match_parent" android:layout_height="wrap_content" ads:adSize="SMART_BANNER" ads:adUnitId="@string/ad_unit_id_wallpaper_full_activity" xmlns:ads="http://schemas.android.com/apk/res-auto"/> </LinearLayout> 。因此处理程序线程正在尝试使用它,但是它已被主线程关闭(在某些时候)。尝试这样的事情:

clientSocket

但是现在处理线程将负责关闭套接字。 clientSocketSocket clientSocket = null; try { clientSocket = serverSocket.accept(); // not automatically closed ... } catch (IOException e) { ... clientSocket.close(); // in case there is an exception from the main loop } 可以在try-with-resources中,因此不必手动关闭它们,也不必使用finally块来手动关闭out