Java如何创建多线程服务器?
Posted borter
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java如何创建多线程服务器?相关的知识,希望对你有一定的参考价值。
在Java编程中,如何创建多线程服务器?
以下示例演示如何使用ServerSocket
类的MultiThreadServer(socketname)
方法和Socket
类的ssock.accept()
方法来创建多线程服务器。
package com.yiibai;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MultiThreadServer implements Runnable {
Socket csocket;
MultiThreadServer(Socket csocket) {
this.csocket = csocket;
}
public static void main(String args[]) throws Exception {
ServerSocket ssock = new ServerSocket(8806);
System.out.println("Server Start and Listening: ");
while (true) {
Socket sock = ssock.accept();
System.out.println("Connected");
new Thread(new MultiThreadServer(sock)).start();
}
}
public void run() {
try {
PrintStream pstream = new PrintStream(csocket.getOutputStream());
for (int i = 100; i >= 0; i--) {
pstream.println(i + " bottles of beer on the wall");
}
pstream.close();
csocket.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
上述代码示例将产生以下结果 -
Server Start and Listening:
示例-2
以下是如何创建多线程服务器的另一个示例。
package com.yiibai;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MultiThreadServer2 {
ServerSocket myServerSocket;
boolean ServerOn = true;
public MultiThreadServer2() {
try {
myServerSocket = new ServerSocket(12345);
} catch(IOException ioe) {
System.out.println("Could not create server socket on port 12345. Quitting.");
System.exit(-1);
}
Calendar now = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy/MM/dd ‘at‘ hh:mm:ss ");
System.out.println("It is now : " + formatter.format(now.getTime()));
while(ServerOn) {
try {
Socket clientSocket = myServerSocket.accept();
ClientServiceThread cliThread = new ClientServiceThread(clientSocket);
cliThread.start();
} catch(IOException ioe) {
System.out.println("Exception found on accept. Ignoring. Stack Trace :");
ioe.printStackTrace();
}
}
try {
myServerSocket.close();
System.out.println("Server Stopped");
} catch(Exception ioe) {
System.out.println("Error Found stopping server socket");
System.exit(-1);
}
}
public static void main(String[] args) {
new MultiThreadServer2();
}
class ClientServiceThread extends Thread {
Socket myClientSocket;
boolean m_bRunThread = true;
public ClientServiceThread() {
super();
}
ClientServiceThread(Socket s) {
myClientSocket = s;
}
public void run() {
BufferedReader in = null;
PrintWriter out = null;
System.out.println("Accepted Client Address - " + myClientSocket.getInetAddress