简单的Java线程TCP服务器线程

时间:2012-10-28 17:38:39

标签: java multithreading networking loops tcp

/*main method*/

Server server = new Server(tcpPort);
new Thread(server).start();

try {

  Thread.sleep(1000*60); /* 60 seconds*/
} catch (InterruptedException e) {
  e.printStackTrace();
}

server.stop;
...

这是我写的代码。启动服务器线程,并运行60秒。如何将其更改为无限运行,当用户通过BufferedReader或其他东西输入Enter时结束。

我用

尝试过
while(!input.equals("")) { /* just pseudocoded here...*/
Thread.sleep(10);   
}

但这将使我的服务器无法正常工作。我的客户甚至不再连接它了。我是否犯了设计错误或者这是一个容易解决的问题?

2 个答案:

答案 0 :(得分:2)

- 试试我写的这个基本聊天服务器。此服务器只是继续在循环中运行,并将客户端发送的消息广播到与此服务器关联的所有其他客户端。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Server {

    // ///----------------------------------------Instance Variable Fields
    ServerSocket ss = null;
    Socket incoming = null;

    // ///----------------------------------------Instance Variable Fields

    // ///---------------------------------------- static Variable Fields
    public static ArrayList<Socket> socList = new ArrayList<Socket>();

    // ///---------------------------------------- static Variable Fields

    public void go() {

        try {

            ss = new ServerSocket(25005);

            while (true) {

                incoming = ss.accept();
                socList.add(incoming);
                System.out.println("Incoming: " + incoming);
                new Thread(new ClientHandleKaro(incoming)).start();

            }

        } catch (IOException e) {

            e.printStackTrace();
        } finally {

            try {
                ss.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    class ClientHandleKaro implements Runnable {

        InputStream is = null;
        OutputStream os = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        PrintWriter pw = null;
        boolean isDone = false;

        Socket sInThread = null;

        public ClientHandleKaro(Socket sxxx) {

            this.sInThread = sxxx;

        }

        @Override
        public void run() {

            if (sInThread.isConnected()) {

                System.out.println("Welcamu Clienta");
                System.out.println(socList);
            }

            try {
                is = sInThread.getInputStream();
                System.out.println("IS: " + is);
                isr = new InputStreamReader(is);
                br = new BufferedReader(isr);

                os = sInThread.getOutputStream();
                pw = new PrintWriter(os, true);

                String s = new String();

                while ((!isDone) && (s = br.readLine()) != null) {

                    String[] asx = s.split("-");
                    System.out.println("On Console: " + s);

                    // pw.println(s);

                    Thread tx = new Thread(new ReplyKaroToClient(s,
                            this.sInThread));
                    tx.start();

                    if (asx[1].trim().equalsIgnoreCase("BYE")) {

                        System.out.println("I am inside Bye");
                        isDone = true;

                    }
                }
            } catch (IOException e) {

                System.out.println("Thanks for Chatting.....");
            } finally {

                try {
                    Thread tiku = new Thread(new ByeByeKarDo(sInThread));
                    tiku.start();
                    try {
                        tiku.join();
                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    }

                    System.out.println("Accha to hum Chalte hain !!!");
                    System.out.println(socList);

                    br.close();
                    pw.close();
                    sInThread.close();

                } catch (IOException e) {

                }
            }

        }

    }

    class ReplyKaroToClient implements Runnable {

        public String mString;
        public Socket mSocket;

        public ReplyKaroToClient(String s, Socket sIn) {

            this.mString = s;
            this.mSocket = sIn;
        }

        @Override
        public void run() {

            for (Socket sRaW : socList) {

                if (mSocket.equals(sRaW)) {
                    System.out.println("Mai same hun");
                    continue;

                } else {
                    try {
                        new PrintWriter(sRaW.getOutputStream(), true)
                                .println(mString);
                    } catch (IOException e) {

                        System.out.println("Its in Catch");

                    }
                }
            }

        }

    }

    class ByeByeKarDo implements Runnable {

        Socket inCom;

        public ByeByeKarDo(Socket si) {

            this.inCom = si;
        }

        @Override
        public void run() {

            try {
                new PrintWriter(inCom.getOutputStream(), true)
                        .println("You have Logged Out of Server... Thanks for ur Visit");
            } catch (IOException e) {

                e.printStackTrace();
            }

        }

    }

    public static void main(String[] args) {

        new Server().go();
    }
}

答案 1 :(得分:0)

从这个SO线程开始:How to create a basic Java Server?。它将为您提供一个如何编写非常简单的服务器的示例。

需要注意的是serverSocket.accept()。它会阻塞 - 换句话说,它会永远等待客户端连接,否则在出现错误时会失败。连接客户端后,您将获得一个clientSocket,您可以使用它来读取客户端编写的内容,并写入它。

这是理解Java网络编程的一个很好的起点。但是,我建议您阅读有关此主题的更多信息。这样的事情:http://beej.us/guide/bgnet/