?? tserver.java
字號:
package server;
import java.io.*;
import java.net.*;
import java.util.*;
import java.sql.*;
import util.*;
public class TServer{
static String info;
static double temperature;
static ArrayList clientList=new ArrayList();
public static void main(String args[]){
ServerSocket svc_socket=null; Svc_thread svc_thread;
Socket c_socket=null;
while(true){
try{
svc_socket=new ServerSocket(12345);
}
catch(IOException e){Debug.println("正在監聽……");}
try{
c_socket=svc_socket.accept();
clientList.add(c_socket);
}
catch(IOException e){Debug.println("正在等待用戶……");}
if(c_socket!=null){
new Svc_thread(c_socket).start();
}
else{continue;}
}//while()
}//main()
}
class Svc_thread extends Thread{
Socket socket1;
DataOutputStream out=null;DataInputStream in=null;
String s=null;
double value=0;
Svc_thread(Socket t){
socket1=t;
try{
in=new DataInputStream (socket1.getInputStream());
out=new DataOutputStream (socket1.getOutputStream());
}
catch(IOException e){}
}
public void run(){
try{
out.writeUTF("rev ready");
out.writeUTF(String.valueOf(TServer.temperature));
Debug.println("發送rev ready&"+TServer.temperature);
}catch(Exception ee){Debug.println("發送失敗");}
while(true){
try{
s=null;
s=in.readUTF();
Debug.println("收到"+s);
if(s.equals("send value")){
Debug.println("send value request accepted");
value=Double.valueOf(in.readUTF()).doubleValue();
Debug.println("收到"+value);
TServer.temperature=value;
sendToAllClient();
}//if
}//try
catch(IOException ee){
Debug.println("一個客戶離開");
TServer.clientList.remove(socket1);//用戶離開時從套接子列表中移除連接;
//不然程序會向已不存在的客戶發數據,進而會使服務端不能正常工作
break;
}
catch(Exception e){break;}
}//while
}//run
/*
向所有客戶發送數據
*/
public void sendToAllClient() throws IOException{
Iterator clients=TServer.clientList.iterator();
DataOutputStream out=null;DataInputStream in=null;
Socket tmpSocket=null;
while(clients.hasNext()){
tmpSocket=(Socket)clients.next();
in=new DataInputStream (tmpSocket.getInputStream());
out=new DataOutputStream (tmpSocket.getOutputStream());
out.writeUTF("rev ready");
out.writeUTF(String.valueOf(TServer.temperature));
Debug.println("sendToAllClient temperature value is "+TServer.temperature);
}
}
}//class
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -