Cấp bậc tác giả:

JAVA

Chương trình server truy cập website để lấy thời tiết

Được viết bởi QuangIT ngày 22/09/2012 lúc 08:34 PM
Chương trình server truy cập website về The Weather around the World (http://www.timeanddate.com/weather/) để lấy thông tin dự báo thời tiết rồi trả về cho client hiển thị lên màn hình.
  • 0
  • 10168

Chương trình server truy cập website để lấy thời tiết

Viết chương trình Client-Server. Chương trình client có giao din cho phép người dùng chn tên thành phtrên thế gii ri gi cho chương trình server (danh sách các thành phố được chương trình server gi vkhi client khi động (server đọc tên thành phtWebsite Weather around the World)). Chương trình server truy cp website vThe Weather around the World (http://www.timeanddate.com/weather/) để ly thông tin dbáo thi tiết ri trvcho client hin thlên màn hình.
thoitiet.jpg

Tại phía Server:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.awt.BorderLayout; 
import java.io.BufferedInputStream;
import java.io.IOException; 
import java.io.InputStream; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.regex.Matcher;
import java.util.regex.Pattern; 

public class URLBai3Server
{
private String url = "http://www.timeanddate.com/weather/";
private ServerSocket server;
DataOutputStream dos;
DataInputStream din;
//--- ham dung 1 doi so--------------------------
public URLBai3Server(int so) throws Exception{
server=new ServerSocket(so);
System.out.println("server started!!!");
}
//--- ham tra ve xau chua ten cac city phan biet boi ki tu '@'-----
 public String init() {
String strcity="";
int i; 
BufferedInputStream bis;
Object ob; 
try { 
URL u = new URL(url);
ob = u.getContent(); 
if (ob instanceof InputStream) {
BufferedInputStream t = new BufferedInputStream((InputStream) ob); 
String st = "";
while ((i = t.read()) > 0) 
{ st = st + (char) i; } 
Pattern pt1 = Pattern.compile("<tr class=c[\\d]>.+?</tr>"); 
Matcher st1 = pt1.matcher(st); 
while (st1.find()) 
{ String st21 = st1.group();
Pattern pt2 = Pattern.compile("<a.+?</a>");
Matcher st2 = pt2.matcher(st21); 
if (st2.find()) { 
String tp = st2.group();
tp = tp.replaceAll("<.+?>", "");
strcity+="@"+tp;
catch (MalformedURLException e) 
{ System.out.println(e); } 
catch (IOException e1)
{ System.out.println(e1); }
return strcity;
 
public static String ConvertC(float c)
{
float de;
de=(c-32)*5/9;
return c + " °C";
}
//---Ham tra ve time cua city co name la nameCity---------------
public float getWeatherOfCity(String nameCity) 
int i; 
String str="0";
BufferedInputStream bis;
Object ob; 
try { 
URL u = new URL(url);
ob = u.getContent();
if (ob instanceof InputStream) { 
BufferedInputStream t = new BufferedInputStream((InputStream) ob);
String st = ""; 
while ((i = t.read()) > 0) 
{ st = st + (char) i; } 
Pattern pt1 = Pattern.compile(">" + nameCity + ".+?class=r.+?F</td>"); 
Matcher st1 = pt1.matcher(st); 
while (st1.find()){ 
String temp = st1.group(); 
temp = temp.replace("</td>", ""); 
temp = temp.replace("&nbsp;&deg;F", "");
temp = temp.replaceAll(">.*>", "");
return Float.parseFloat(temp);
catch (MalformedURLException e) { System.out.println(e); } 
catch (IOException e1) { System.out.println(e1); }
return Float.parseFloat(str);
}
//-----ham chay cua server---------------------------------------
public void run(){
try{
boolean ck=true;
Socket sk= server.accept();
dos= new DataOutputStream(sk.getOutputStream());
din = new DataInputStream(sk.getInputStream());
while(true)
{
if(ck){
dos.writeUTF(init());
ck=false;
}
String ct = din.readUTF();
dos.writeUTF(ConvertC(getWeatherOfCity(ct)));
}
}
catch(Exception e){
}
}
//--- ham main--------------------------------------------------
public static void main(String[] args) throws Exception
{
URLBai3Server ser= new URLBai3Server(7777);
ser.run();
}
}

Tại phía Client:
import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.net.Socket; 
import java.util.*; 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class URLBai3Client extends Thread{ 
DataInputStream din;
DataOutputStream dos;
Socket socket;
private String sendMess;
private String revMess;
private String userName="";
//--- ham dung khong doi so----------------------------------
public URLBai3Client() throws Exception{
socket = new Socket("localhost", 7777);
din = new DataInputStream(socket.getInputStream()); 
        dos = new DataOutputStream(socket.getOutputStream());
        sendMess="Wellcome";
}
//--- ham gan gia tri xau se duoc gui di---------------
public void setSendMess(String mes)
{
sendMess=mes;
}
//--- ham gan gia tri khac cho xau nhan----------------
public void setRevMess(String mes)
{
revMess=mes;
}
//-------ham lay gia tri cua revMess----
public String getRevMess()
{
return revMess;
}
//--- ham gui xau messLog len server------------------
public void sendMessLog(String messLog) throws Exception
{
dos.writeUTF(messLog);
}
//--- ham run (overwrite)------------------
public void run(){
try{
while(true) {  
revMess=din.readUTF();
String st= revMess.substring(0,1);
if(st.equals("@"))
{
String[] arrct= revMess.split("@");
for(int i=0;i<arrct.length;i++)
URLBai3GuiClient.jComboBox.addItem(arrct[i]);
}
else
URLBai3GuiClient.jLabel.setText(revMess);
dos.flush();
}
}
catch(Exception e){}        
}
 }

GUIClient:
import java.awt.BorderLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener;  
import javax.swing.*; 
public class URLBai3GuiClient extends JFrame implements ActionListener{ 
URLBai3Client t;
static JComboBox jComboBox = new JComboBox();
static JLabel jLabel = new JLabel("Please choice name City and press OK");
private JButton button = new JButton("DisPlay"); 
private String url = "http://www.timeanddate.com/weather/";
private JPanel main = new JPanel();
private JPanel jp1= new JPanel(); 
private JPanel jp2= new JPanel();
private JPanel jp3= new JPanel();
//---- ham dung ko doi so--------------------
public URLBai3GuiClient() throws Exception{ 
super("Time");
t=new URLBai3Client();
t.start();
jp1.add(jComboBox); 
jp2.add(jLabel); 
jp3.add(button);
main.setLayout(new BorderLayout()); 
main.add(jp1, BorderLayout.NORTH); 
main.add(jp2, BorderLayout.CENTER); 
main.add(jp3, BorderLayout.SOUTH); 
button.addActionListener(this);
this.setContentPane(main);
this.setSize(300,150);
this.show();
this.setVisible(true);
//---- ham lang nghe su kien--------------------
public void actionPerformed(ActionEvent ae)
{
try{
if(ae.getSource()==button)
{
String st = jComboBox.getSelectedItem().toString();
t.sendMessLog(st);
}
}
catch(Exception e)
{System.out.print(e);}
}
//-----ham main---------------------------------
public static void main(String arg[]) throws Exception { 
URLBai3GuiClient cli= new URLBai3GuiClient(); 
}

Nguồn bài viết: Dngaz.com

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML