Giải pháp kỹ thuật tăng số gia:

Một phần của tài liệu tiểu luận môn lập trình mạng đồng bộ hóa và gắn bó dữ liệu thông qua một bài toán cụ thể (Trang 26)

Để tăng số gia cho mỗi lần sự kiện đến, đầu tiên số gia = 0, với mỗi sự kiện đến số gia tăng lên 1. Sau đây là chương trình Congto, chương trình cho phép Server nhận thông điệp, xử lý và hiển thị các thông điệp.

import java.net.*; import java.io.*; import javax.swing.*;

//Khi nhan duoc ket noi tu tram khac, chuong trinh se giao cong viec //cho mot luong xu ly.

public class Congto extends Thread{

// Variables declaration - GEN-BEGIN:variables

Socket client; BufferedReader in; PrintWriter out; String strMes; JTextArea txtRecv; JLabel lblClock; int slave;

// End of variables declaration - GEN-END:variables

public Congto(Socket client,int slave, JTextArea txtRecv, JLabel lblClock){ this.client=client; this.txtRecv = txtRecv; this.lblClock = lblClock; this.slave = slave; try{

//Lay ve luong nhap de nhan du lieu tu tram khac gui den

in = new BufferedReader(new InputStreamReader(client.getInputStream()));

//Lay ve luong xuat de gui du lieu cho tram khac

out = new PrintWriter(client.getOutputStream(), true); }catch(Exception e){

} }

public void run(){ try {

//Doc thong diep do tram khac gui den

strMes = in.readLine(); if (strMes!=null){

//Lay cac thong tin trong thong diep: clock#code|message

String strClockRev = strMes.substring(0,strMes.indexOf("#")); int intClockRev = Integer.parseInt(strClockRev);

//tang gia tri cua cong to sự kiện lên

int intClock = intClockRev+1;

//Hien thi thong diep vao text area tren form

String strCode = strMes.substring(strMes.indexOf("#") +1,strMes.indexOf("|"));

String strContent = strMes.substring(strMes.indexOf("|") +1,strMes.length());

txtRecv.append("*Message from: " + getInfoClient()+"\n");

txtRecv.append(" Lan goi: " + Integer.toString(intClock) +"\n"); txtRecv.append(" Noi dung: " + strContent +"\n");

lblClock.setText(Integer.toString(intClock)); }

} }

catch (IOException ex) { }

}

//Lay thong tin tram da ket noi

public String getInfoClient(){ (adsbygoogle = window.adsbygoogle || []).push({});

String host = client.getInetAddress().getHostName(); String addr = client.getInetAddress().getHostAddress(); int port = client.getPort()-slave;

return host + " (" + Integer.toString(port)+")"; }

//Gui du lieu cho tram da ket noi

public void sendMessage(String message) throws Exception { out.println(message);

} }

Một phần của tài liệu tiểu luận môn lập trình mạng đồng bộ hóa và gắn bó dữ liệu thông qua một bài toán cụ thể (Trang 26)