BT HPT
TCP SOCKET
Server.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class Server {
public static void main(String [] args){
BufferedReader br;
PrintWriter pw;
ServerSocket ssk;
Socket socket;
String str="";
try{
System.out.println("Server start");
ssk=new ServerSocket(1234);
socket=new Socket();
socket=ssk.accept();
br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw=new PrintWriter(socket.getOutputStream(),true);
pw.println("Server say: Hello Client");
while(true){
System.out.println("Doc du lieu tu may khach");
System.out.println(br.readLine());
System.out.print("Connection...");
}
}
catch(UnknownHostException unKnHostE){
unKnHostE.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
}
Client.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String []args){
Socket socket;
BufferedReader br;
PrintWriter pw;
String str="";
try{
socket=new Socket("localhost",1234);
//noi dung cua Client can gui qua cho Server
pw=new PrintWriter(socket.getOutputStream(),true);
pw.println("Hello Server");
//noi dung Server gui qua socket duoc doc va luu vao BufferReader
br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
while((str=br.readLine())!=null){
System.out.println(str);
}
pw.close();
br.close();
}catch(UnknownHostException unhost){
unhost.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
UDP SOCKET
Server.java
import java.net.*;
public class Server {
public static void main(String [] args){
DatagramPacket dp;
DatagramSocket ds = null;
byte[] buf=new byte[20];
try{
ds=new DatagramSocket(1234);
System.out.print("Server started.");
while(true){
dp=new DatagramPacket(buf, buf.length);
ds.receive(dp);
buf=dp.getData();
String str=new String(buf);
System.out.print(str);
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
Client.java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Client {
public static void main(String [] args){
DatagramPacket dp;
DatagramSocket ds=null;
String str="Hello Server";
byte [] b=str.getBytes();
try{
ds=new DatagramSocket();
InetAddress ip=InetAddress.getByName("localhost");
dp=new DatagramPacket(b, b.length, ip, 1234); //datapacket mang data, d?a ch? ip, s? c?ng
ds.send(dp);
}catch(Exception e){
e.printStackTrace();
}
}
}
Bài 2: Viết UDP Socket,đảo chuỗi
Server.java
import java.net.*;
public class Server {
public static void main(String [] args){
DatagramPacket dp;
DatagramSocket ds = null;
byte[] buf=new byte[256];
byte[] b;
try{
//nhan chuoi du lieu tu Client
ds=new DatagramSocket(1234);
System.out.println("Chay o Server");
while(true){
dp=new DatagramPacket(buf, buf.length);
ds.receive(dp);
buf=dp.getData();
String str=new String(buf);
String dao=new DaoString(str).getString();
System.out.println("Chuoi da duoc dao lai: "+dao);
System.out.println("Dang gui tra du lieu ve cho Client");
//gui datapacket lai cho Client
b=dao.getBytes();
ds=new DatagramSocket();
InetAddress Cip=dp.getAddress();
int Cport=dp.getPort();
dp=new DatagramPacket(b, b.length, Cip, Cport);
ds.send(dp);
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
class DaoString {
String s;
public DaoString(String in){
int len = in.length();
char outChars[] = new char[len];
for(int i=0;i<len;++i)
outChars[len-1-i]=in.charAt(i);
s = String.valueOf(outChars);
}
public String getString(){
return s;
}
}
Client.java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Client {
public static void main(String [] args){
DatagramPacket dp;
DatagramSocket ds=null;
BufferedReader reader;
String str;
byte [] b;
byte[] buf = new byte[256];
try{
//nhap chuoi
System.out.print("Nhap Chuoi Vao: ");
reader = new BufferedReader(new InputStreamReader(System.in));
str = reader.readLine();
System.out.println("Dang Gui Chuoi qua Server...");
//gui datapacket qua server
b=str.getBytes();
ds=new DatagramSocket();
InetAddress ip=InetAddress.getByName("localhost");
dp=new DatagramPacket(b, b.length, ip, 1234);
ds.send(dp);
//nhan datapacket gui ve tu Server
dp = new DatagramPacket(buf, buf.length);
ds.receive(dp); //buf = packet.getData();
str = new String(dp.getData()).trim(); //data = new String(buf).trim();
System.out.println("Data returned from Server: " + str);
}catch(Exception e){
e.printStackTrace();
}
}
}
Bài 3:Viết TCP Socket đếm số từ có trong chuỗi
Server.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
public class Server {
public static void main(String[] args) {
ServerSocket serverSocket;
Socket socket;
String data;
Boolean finished=true;
try {
serverSocket = new ServerSocket(2002);
System.out.println("Server is listening..");
socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
while(finished) {
data = reader.readLine();
System.out.println("Data received from Client: " + data);
//Dem so ki tu,tra ve cho Client
writer.println(Dem(data));
}
serverSocket.close();
socket.close();
reader.close();
} catch(Exception e) {
e.printStackTrace();
}
}
/*
static int countWords(String data) {
StringTokenizer st = new StringTokenizer(data, " ");
int count = st.countTokens();
return count;
} */
public static int Dem(String in){
int len = in.length();
int dem=1;
for(int i=0;i<len;++i)
{
//kiem tra neu' ki tu la' space hoac , hoac .
if(( in.charAt(i)==32) || ( in.charAt(i)==44) || ( in.charAt(i)==46))
{
dem=dem+1;
}
}
return dem;
}
}
Client.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
Socket socket;
BufferedReader reader, stdIN;
PrintWriter writer;
String data;
try {
socket = new Socket("localhost", 2002);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
System.out.print("Enter a message: ");
stdIN = new BufferedReader(new InputStreamReader(System.in));
data = stdIN.readLine();
writer.println(data);
while ((data = reader.readLine()) != null)
System.out.println("Result returned from Server: " + data);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Bài 4: Viết JavaRMI,tính add,sub
Calculator.java
import java.rmi.*;
public interface Calculator extends Remote{
public int add(int x,int y) throws RemoteException;
public int sub(int x,int y) throws RemoteException;
}
CalculatorIplm.java
import java.rmi.*;
public class CalculatorImpl implements Calculator{
public int add(int x,int y) throws RemoteException{
System.out.println("Tong Cua 2 so la:");
return (x+y);
}
public int sub(int x,int y) throws RemoteException{
System.out.println("Hieu Cua 2 so la:");
if(x>=y)
return (x-y);
else
return (y-x);
}
}
CalculatorServer.java
import java.rmi.*;
import java.rmi.server.*;
public class CalculatorServer{
public static void main(String args[])
{
try
{
CalculatorImpl c=new CalculatorImpl();
System.out.println("Tinh toan...");
//thông báo s? hi?n di?n c?a d?i tu?ng cho máy do Java
UnicastRemoteObject.exportObject(c);
// dang ky doi tuong voi bo quan ly RMI
Naming.bind("rmi://localhost/MyCalculator",c);
System.out.println("Dang Ky");
}
catch (Exception e)
{
System.out.println(e);
}
}
}
CalculatorClient.java
import java.rmi.*;
public class CalculatorClient{
public static void main(String args[])
{
try
{
System.out.println("Tim kiem doi tuong...");
Calculator c=(Calculator)Naming.lookup("rmi://localhost/MyCalculator");
//Goi Phuong Thuc Cua Doi Tuong
System.out.println(c.add(5,8));
System.out.println(c.sub(5,8));
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Bài 4: k giao diện
PhepTinhIn.java
import java.rmi.server.*;
import java.rmi.*;
import java.net.*;
public interface PhepTinhIn extends Remote{
public double Sub(double a,double b)throws RemoteException;
public double Add(double a,double b)throws RemoteException;
public double Prod(double a,double b)throws RemoteException;
public double Div(double a,double b) throws RemoteException;
}
PhepTinhRMI.java
import java.rmi.server.*;
import java.rmi.*;
import java.net.*;
public class PhepTinhRMI implements PhepTinhIn{
public double Sub(double a,double b) throws RemoteException{
return a-b;
}
public double Add(double a,double b) throws RemoteException{
return a+b;
}
public double Prod(double a,double b) throws RemoteException{
return a*b;
}
public double Div(double a,double b) throws RemoteException{
return a/b;
}
}
Server.java
import java.rmi.server.*;
import java.rmi.*;
import java.net.*;
public class Server {
public static void main (String[] args) {
try{
/*Khoi tao doi tuong ket noi tu xa*/
PhepTinhIn h = new PhepTinhRMI();
UnicastRemoteObject.exportObject(h);
System.out.println("Tao doi tuong cho server ......");
/*Tao ket noi voi vong lap vo thoi han*/
Naming.rebind("rmi://127.0.0.1/PhepTinh",h);
System.out.println("Dang mo ket noi tren Server ......");
}
catch(Exception es){
System.out.println(es);
}
}
}
Client.java
import java.rmi.server.*;
import java.net.*;
import java.rmi.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client implements ActionListener{
PhepTinhIn h;
/*Phuong thuc tao giao dien cho chuong trinh*/
Button b[];
TextField []t;
String[]bu ={"Tong","Tich","Thuong","Hieu","Reset","Thoat"};
Label []l;
String []la ={"Nhap a =","Nhap b = ","Ket Qua "};
Frame f;
public Client1(){
f= new Frame("Design-Vo Van Quan");
f.setLayout(null);
Label lab = new Label("CHUONG TRINH RMI");
lab.setBounds(100,30,200,30);
f.add(lab);
/*Tao cac Label va TextField*/
t = new TextField[3];
l = new Label[3];
for(int i =0;i<3;i++){
l[i] = new Label(la[i]);
t[i] = new TextField("0");
l[i].setBounds(10,100+i*35,80,25);
t[i].setBounds(100,100+i*35,100,25);
f.add(t[i]);
f.add(l[i]);
}
/*Tao cac nut bam*/
b = new Button[6];
for(int i =0;i<6;i++){
b[i] = new Button(bu[i]);
b[i].setBounds(230,60+i*30,100,25);
f.add(b[i]);
b[i].addActionListener(this);
}
/*Thuc hien thao tac tren Form*/
f.setVisible(true);
f.setSize(360,280);
}
/*Phuong thuc xu ly cac su kien*/
public void actionPerformed(ActionEvent e){
double a1 = Double.parseDouble(t[0].getText());
double b1 = Double.parseDouble(t[1].getText());
try{
/*Tong cua 2 so*/
if(e.getSource()==b[0]){
this.Connect();
t[2].setText("Tong s = "+h.Add(a1,b1));
}
/*Tich cua 2 so*/
else if(e.getSource()==b[1]){
this.Connect();
t[2].setText("Tich p = "+h.Prod(a1,b1));
}
/*Thuong cua 2 so*/
else if(e.getSource()==b[2]){
this.Connect();
t[2].setText("Thuong d = "+h.Div(a1,b1));
}
/*Hieu 2 so*/
else if(e.getSource()==b[3]){
this.Connect();
t[2].setText("Hieu h = "+h.Sub(a1,b1));
}
else if(e.getSource()==b[4]){
for(int i=0;i<3;i++){
t[i].setText("0");
}
}
else if(e.getSource()==b[5]){
System.exit(0);
}
}
catch(Exception es){
System.out.println(es);
}
}
public static void main (String[] args) {
Client1 x = new Client1();
}
/*Phuong thuc mo ket noi den Server*/
public void Connect(){
try{
/*Tao doi tuong cho lop trieu goi*/
h = (PhepTinhIn)Naming.lookup("rmi://127.0.0.1/PhepTinh");
System.out.println("Client ket noi den server.....");
}
catch(Exception es){
System.out.println(es);
}
}
}
Bạn đang đọc truyện trên: AzTruyen.Top