简单的 Java Threaded TCP Server 线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13111308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple Java Threaded TCP Server thread
提问by user1781173
/*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;
...
This is the code I've written. A Server thread is started, and runs for 60 seconds. How do I change this to run infinitely, ending when a user enters Enter via a BufferedReader or something.
这是我写的代码。服务器线程启动,并运行 60 秒。如何将其更改为无限运行,当用户通过 BufferedReader 或其他方式输入 Enter 时结束。
I've tried it with
我试过了
while(!input.equals("")) { /* just pseudocoded here...*/
Thread.sleep(10);
}
but this will my Server stop from working correctly. My clients won't even connect to it anymore. Have I made a design mistake or is this an easy problem to solve?
但这将使我的服务器停止正常工作。我的客户甚至不会再连接到它。我犯了一个设计错误还是这是一个容易解决的问题?
回答by Kumar Vivek Mitra
-Try this basic Chatting Server written by me. This server simply keeps running in loop and broadcast the message send by the clients to all the other clients associated with this server.
-试试我写的这个基本的聊天服务器。该服务器只是保持循环运行,并将客户端发送的消息广播到与该服务器关联的所有其他客户端。
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();
}
}
回答by DejanLekic
Start with this SO thread: How to create a basic Java Server?. It will give you an example how to write a very simple server.
从这个 SO 线程开始:How to create a basic Java Server? . 它将为您提供如何编写一个非常简单的服务器的示例。
Key thing to note there is the serverSocket.accept()
. It will block - in other words it will WAIT forever for a client to connect, or it will fail in the case of some error. Once a client is connected, you will get a clientSocket that you can use to read what client wrote, and also write to it.
需要注意的关键是serverSocket.accept()
. 它会阻塞——换句话说,它将永远等待客户端连接,或者在出现某些错误的情况下它会失败。连接客户端后,您将获得一个 clientSocket,您可以使用它来读取客户端写入的内容,也可以向其中写入内容。
It is really a good starting point for understanding Java network programming. However, I recommend you read more about this topic. Something like this: http://beej.us/guide/bgnet/
它确实是理解 Java 网络编程的一个很好的起点。但是,我建议您阅读有关此主题的更多信息。像这样的东西:http: //beej.us/guide/bgnet/