摘要
Java是伴隨Internet的大潮產生的
一
在Java之前
Java軟件包內在支持的網絡協議為TCP/IP
public class ServerSocket
{
public ServerSocket(int port) throws IOException
public Socket accept() throws IOException
public InetAddress getInetAddress()
public int getLocalPort()
public void close() throws IOException
public synchronized void setSoTimeout (int timeout) throws SocketException
public synchronized int getSoTimeout() throws IOException
}
ServerSocket構造器是服務器程序運行的基礎
Java的多線程可謂是Java編程的精華之一
Java中實現線程的方式有兩種
二
以下是我們在項目中采用的多線程服務器程序的架構
file://類receiveServer
import java
import java
import java
public class receiveServer
{
final int RECEIVE_PORT=
file://該服務器的端口號
file://receiveServer的構造器
public receiveServer()
{
ServerSocket rServer=null; file://ServerSocket的實例
Socket request=null; file://用戶請求的套接字
Thread receiveThread=null;
try
{
rServer=new ServerSocket(RECEIVE_PORT); file://初始化ServerSocket
System
System
System
System
while(true)
{
file://等待用戶請求
request=rServer
file://接收客戶機連接請求
receiveThread=new serverThread(request);
file://生成serverThread的實例
receiveThread
file://啟動serverThread線程
}
}
catch(IOException e)
{
System
}
}
public static void main(String args[])
{
new receiveServer();
} file://end of main
} file://end of class
file://類serverThread
import java
import java
class serverThread extends Thread
{
Socket clientRequest; file://用戶連接的通信套接字
BufferedReader input; file://輸入流
PrintWriter output; file://輸出流
public serverThread(Socket s)
{
file://serverThread的構造器
this
file://接收receiveServer傳來的套接字
InputStreamReader reader;
OutputStreamWriter writer;
try
{
file://初始化輸入
reader=new InputStreamReader(clientRequest
writer=new OutputStreamWriter(clientRequest
input=new BufferedReader(reader);
output=new PrintWriter(writer
}
catch(IOException e)
{
System
}
output
output
output
}
public void run()
{
file://線程的執行方法
String command=null; file://用戶指令
String str=null;
boolean done=false;
while(!done)
{
try
{
str=input
}
catch(IOException e)
{
System
}
command=str
if(str==null || command
done=true;
else if(command
{
file://命令help查詢本服務器可接受的命令
output
output
output
}
else if(command
{
file://命令query
output
}
//else if ……
else if(!command
{
output
}
}//end of while
try
{
clientRequest
}
catch(IOException e)
{
System
}
command=null;
}//end of run
啟動該服務器程序後
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27667.html