3. Xây dựng chương trình hội thoại chat room Client/Server hoạt động theo giao
thức TCP/IP
3.1.Chương trình:
//Server
package Bai3;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
public class Server {
public final static int daytimePort = 5000;
public Vector<ThreadedHandler> cls=new Vector<ThreadedHandler>();
public Server(){
ServerSocket theServer;
Socket theConnection;
try {
theServer = new ServerSocket(daytimePort);
while (true) {
theConnection = theServer.accept();
System.out.println("Have Connection!");
new ThreadedHandler(this,theConnection).start();
}
}catch (IOException e) { System.err.println(e); }}
public static void main(String[] args) {new Server(); }
public class ThreadedHandler extends Thread{
Server sv;
public Socket incoming;
public DataInputStream dis;
public DataOutputStream dos;
public String name;
public ThreadedHandler(ChatRoomServer sv, Socket i)
{
this.sv=sv;
this.incoming=i;
try{
this.dis = new DataInputStream(incoming.getInputStream());
this.dos = new DataOutputStream(incoming.getOutputStream());
}catch(IOException e){}}
public void run(){
String ch="";
try{
ch = dis.readUTF();
String cmd=ch.substring(0, ch.indexOf(","));
String msg=ch.substring(ch.indexOf(",")+1);
if (!cmd.equals("Joint")) incoming.close();
System.out.println("Hello "+msg);
this.name=msg;
this.sv.cls.add(this);
while (true)
{
ch = dis.readUTF();
cmd=ch.substring(0, ch.indexOf(","));
msg=ch.substring(ch.indexOf(",")+1);
if (cmd.equals("Msg")) {
for (int i=0;i
ThreadedHandler temp=this.sv.cls.get(i);
if (temp!=this){
temp.dos.writeUTF("Msg,"+this.name+">>"+msg);}}}
else{ incoming.close();
this.sv.cls.remove(this);}} }catch(IOException e)
{sv.cls.remove(this);}}}}
//Client ChatRoom
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Client {
public JFrame frame;
public JTextArea Room;
public JTextField msg;
public JTextArea Joiners;
public String NickName;
public Socket soc;
public DataInputStream dis;
public DataOutputStream dos;
public Client(String NickName){
this.NickName = NickName;
this.frame = new JFrame("Chat Room!");
this.frame.setSize(480 ,400);
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.setLayout(null);
JLabel lr=new JLabel("Chat room! Hello "+this.NickName);
lr.setBounds(20, 10, 300, 25);
this.frame.add(lr);
this.Room=new JTextArea("");
this.Room.setBounds(20, 50, 300, 250);
this.Room.setEditable(false);
this.frame.add(Room);
JLabel lsd=new JLabel("Send");
lsd.setBounds(20, 325, 50, 25);
this.frame.add(lsd);
this.msg=new JTextField("");
this.msg.setBounds(100, 325, 200, 25);
msg.addActionListener(new SendActionListener(this));
this.frame.add(msg);
JButton OK=new JButton("Send");
OK.setBounds(320, 325, 80, 25);
OK.addActionListener(new SendActionListener(this));
this.frame.add(OK);
JLabel lj=new JLabel("Joiners");
lj.setBounds(620, 10, 50, 50);
this.frame.add(lj);
this.Joiners = new JTextArea("");
this.Joiners.setBounds(330, 50, 120, 250);
this.Joiners.setEditable(false);
this.frame.add(Joiners);
frame.setVisible(true);
try{
soc = new Socket("localhost", 5000);
this.dis = new DataInputStream(soc.getInputStream());
this.dos = new DataOutputStream(soc.getOutputStream());
new ThreadedHandler(this).start();
this.dos.writeUTF("Joint,"+this.NickName);
}catch(IOException e){this.frame.dispose();}
}
public class SendActionListener implements ActionListener{
Client cr;
public SendActionListener(Client cr){
this.cr = cr; }
public void actionPerformed(ActionEvent e) {
if (!cr.msg.getText().equals("")){
cr.Room.setText(cr.NickName+"> "+cr.msg.getText()
+"\n"+cr.Room.getText());
try{ this.cr.dos.writeUTF("Msg,"+cr.msg.getText());
}catch(IOException e1){cr.frame.dispose();new LoginFrame("");}
cr.msg.setText("");}}}
public class ThreadedHandler extends Thread{
Client cr;
public ThreadedHandler(ChatRoom cr){
this.cr=cr; }
public void run(){
String ch="";
try{
while (true){
ch = dis.readUTF();
String cmd=ch.substring(0, ch.indexOf(","));
String msg=ch.substring(ch.indexOf(",")+1);
if (cmd.equals("Msg"))
this.cr.Room.setText(msg+"\n"+cr.Room.getText());
else this.cr.soc.close();}
}catch(IOException e){cr.frame.dispose();new LoginFrame("");}}}}
//Xuly ChatRoom
public class LoginFrame {
public JFrame frame;
public LoginFrame(String ms){
frame = new JFrame("Login");
frame.setSize(400 ,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
JLabel lname=new JLabel("Name");
lname.setBounds(50, 50, 50, 50);
frame.add(lname);
final JTextField Name=new JTextField("");
Name.setBounds(120, 50, 200, 50);
frame.add(Name);
final JLabel msg=new JLabel("Msg:"+ms);
msg.setBounds(120, 200, 200, 50);
frame.add(msg);
JButton OK=new JButton("Login");
OK.setBounds(120, 120, 200, 50);
OK.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
if (!Name.getText().equals("")){
new Client(Name.getText());
frame.dispose();}
else msg.setText("Msg: Please input your name!"); }});
frame.add(OK); frame.setVisible(true);}
public static void main(String[] args){new LoginFrame("");}}
1. Xây dựng chương trình hội thoại Client/Server hoạt động theo giao thức
UDP
+ Đổi chuỗi đã gửi thành chuỗi in hoa
+ Đổi chuỗi đã gửi thành chuỗi thường
+ Đếm số từ của chuỗi đã gửi
1.1.Chương trình:
//Server
package Bai1;
import java.io.IOException;
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(5000);
byte [] send;
byte [] receive = new byte[1024];
System.out.println("server is ready");
while(true)
{
Xuly xuly = new Xuly();
DatagramPacket receivePac = new DatagramPacket(receive, receive.length);
socket.receive(receivePac);
String chuoi = new
String(receivePac.getData()).substring(0,receivePac.getLength());
System.out.println("Chuoi nhan duoc tu Client: "+chuoi);
String Hoa = xuly.Hoa(chuoi);
String Thuong = xuly.Thuong(chuoi);
String sotu = xuly.DemSoTu(chuoi)+"";
send = (Hoa+Thuong+sotu).getBytes();
int Port = receivePac.getPort();
InetAddress IP = receivePac.getAddress();
DatagramPacket sendPac = new DatagramPacket(send,send.length,IP,Port);
socket.send(sendPac);}}}
//Client
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
Scanner nhap = new Scanner(System.in);
DatagramSocket socket = new DatagramSocket();
byte [] send;
byte [] receive = new byte[1024];
InetAddress IP = InetAddress.getByName("localhost");
int Port = 5000;
while(true)
{
System.out.print("Nhap chuoi can xu ly: ");
String chuoi = nhap.nextLine();
chuoi = chuoi.trim();
int l = chuoi.length();
send = chuoi.getBytes();
DatagramPacket sendPac = new DatagramPacket(send, send.length,IP,Port);
socket.send(sendPac);
DatagramPacket receivePac = new DatagramPacket(receive, receive.length);
socket.receive(receivePac);
String ketqua=new
String(receivePac.getData()).substring(0,receivePac.getLength());
String Hoa = ketqua.substring(0,l);
String Thuong = ketqua.substring(l,2*l);
String SoTu = ketqua.substring(3*l,ketqua.length());
System.out.println("In ra chuoi Hoa: "+Hoa);
System.out.println("In ra chuoi Thuong: "+Thuong);
System.out.println("So tu cua chuoi: "+SoTu);}}}
//Xuly
public class Xuly {
public String Hoa(String s)
{
s=s.trim();
String tam="";
for(int i=0;i
{
char c=s.charAt(i);
if(c>='a' && c<'z' ) c = (char) (c-32);
tam+=c; } return tam; }
public String Thuong(String s)
{
s=s.trim();
String tam="";
for(int i=0;i
{
char c=s.charAt(i);
if(c>='A' && c<='Z') c=(char)(c+32);
tam+=c;
} return tam; }
public int DemSoTu(String s)
{
int count =0;
try{
for(int i=0;i
{
if(s.charAt(i)==' ' && s.charAt(i+1)!=' ' && s.charAt(i+1)!='\0')
{count++;}}
if(s.charAt(0)!=' ') count++;
return count;
}catch(Exception e){ return count; }}
public static void main(String[] args) {
Xuly xuly = new Xuly();
System.out.println(xuly.DemSoTu("Truong Phi")); }}
2. Xây dựng chương trình hội thoại Client/Server hoạt động theo giao thức
UDP
- Chương trình Client cho phép nhập vào từ bàn phím một chuỗi biễu diễn một
phép tính gồm các toán tử +, -, (, ).
Ví dụ:
-
5+13-(12-4*6) –((3+4)-5)
Chương trình Server thực hiện tính toán và trả kết quả về cho Client.
2.1.Chương trình
//Server
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class Server {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(5000);
byte [] receive = new byte[1024];
byte [] send ;
System.out.println("server is ready");
while(true)
{
DatagramPacket receivePac = new DatagramPacket(receive, receive.length);
socket.receive(receivePac);
String chuoi = new
String(receivePac.getData()).substring(0,receivePac.getLength());
System.out.println("Chuoi nhan duoc tu client: "+chuoi);
//gui di
XuLy xuly = new XuLy();
send = xuly.calculate(chuoi).getBytes();
int Port = receivePac.getPort();
InetAddress IP = receivePac.getAddress();
DatagramPacket sendPac = new DatagramPacket(send, send.length,IP,Port);
socket.send(sendPac);}}}
//Client
public class Client {
public static void main(String[] args) throws IOException {
Scanner nhap = new Scanner(System.in);
DatagramSocket socket = new DatagramSocket();
int Port = 5000;
InetAddress IP = InetAddress.getByName("localhost");
byte [] receive = new byte[1024];
byte [] send ;
while(true)
{
System.out.print("Nhap chuoi can xu ly: ");
String chuoi = nhap.nextLine();
//gui chuoi can xu ly cho server
send = chuoi.getBytes();
DatagramPacket sendPac = new DatagramPacket(send, send.length,IP,Port);
socket.send(sendPac);
//nhan xu ly tu phia server
DatagramPacket receivePac = new DatagramPacket(receive, receive.length);
socket.receive(receivePac);
String ketqua = new String(receivePac.getData()).substring(0,receivePac.getLength());
System.out.println("Ket qua: "+ketqua);}}}
//Xuly
import java.util.Stack;
public class XuLy {
private int Priority(char c) {
if (c == '+' || c == '-') return 1;
if (c == '*' || c == '/') return 2;
if (c == '^' || c == '#') return 3;
return 0;
}
private boolean IsNumber(char c) {
return (c >= '0' && c <= '9') || (c == '.');}
private String convert(String st) {
// dau # quy uoc cho sqrt
st = st.replaceAll("sqrt", "#");
System.out.println(st);
String result = "";
Stack<Character> stack = new Stack<Character>();
try {
for (int i = 0; i < st.length(); i++) {
System.out.println("result " + result);
//neu la phep toan
if (st.charAt(i) == '+' || st.charAt(i) == '-'
|| st.charAt(i) == '/' || st.charAt(i) == '*'
|| st.charAt(i) == '^' || st.charAt(i) == '#') {
if (stack.size() > 0) {
try {
while (Priority(stack.peek()) >= Priority(st
.charAt(i))) {
result += stack.pop(); }
catch (Exception e) {}}
stack.push(st.charAt(i)); }
//neu la so
if (st.charAt(i) >= '0' && st.charAt(i) <= '9') {
int pos = i;
//liem tra cac vi tri tiep theo co phai so hay khong
while (IsNumber(st.charAt(i))) {
i++;
if (i == st.length())
break;}
}
result += st.substring(pos, i) + " ";
i--;//vi lat nua quay tro lai vong lap for chinh i se tang len
}
// push dau (
if (st.charAt(i) == '(' )
stack.push( '(' );
// gap dau ) se dua cac phep toan trong stack ra
if (st.charAt(i) == ')') {
char tmp = stack.pop();
while (tmp != '(') {
result += tmp;
tmp = stack.pop(); }}}
while (!stack.empty())
result += stack.pop();
} catch (Exception e) {
return "Error"; }
System.out.println("resultt o day la:"+result);
return result;}
public String calculate(String st) {
int S = 0;
String bl = convert(st).trim();
if (bl.compareTo("Error") == 0) return "Error";
bl += " ";
Stack<Float> stack = new Stack<Float>();
float a, b;
try {
for (int i = 0; i < bl.length(); i++) {
System.out.println("kt: " + bl + " " + i);
switch (bl.charAt(i)) {
case '*':
a = stack.pop();
b = stack.pop();
stack.push(a * b); break;
case '/':
a = stack.pop();
b = stack.pop();
if (a == 0)
return "Error";
stack.push(b / a);break;
case '-':
a = stack.pop();
b = stack.pop();
stack.push(b - a);break;
case '+':
a = stack.pop();
b = stack.pop();
stack.push(a + b); break;
default: {
if (IsNumber(bl.charAt(i))) {
int pos = i;
i = bl.indexOf(" ", pos);
stack.push(Float.parseFloat(bl.substring(pos, i)));
} else if (bl.charAt(i) != ' ') {
return "Error";
}
} }}} catch (Exception e) { return "Error"; }
if (stack.size() > 1)
return "Error";
return stack.pop() + "";}}
3. Xây dựng chương trình hội thoại chat room Client/Server hoạt động theo
giao thức UDP
3.1.Chương trình :
//Server
package Bai3;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Vector;
public class Server {
DatagramSocket soc;
byte[] receiveData = new byte[1024];
DatagramPacket pac;
public Vector<InetAddress> IP=new Vector<InetAddress>();
public Vector<Integer> port = new Vector<Integer>();
public static void main(String[]args){
new Server();
}
public Server(){
try {
soc = new DatagramSocket(5000);
Socket cl;
pac = new DatagramPacket(receiveData, receiveData.length);
while (true){
soc.receive(pac);
String st = new String(pac.getData()).substring(0, pac.getLength());
try{
if (st.charAt(0)=='$' && st.charAt(1)=='$'){
IP.add(pac.getAddress());
port.add(pac.getPort());
System.out.println(""+IP.size()); continue;
}
}catch(Exception e){}
for (int i=0; i
send(st,IP.get(i),port.get(i)); }} catch (IOException e) {} }
public void send(String st, InetAddress IPAddress,int port) throws IOException{
byte[] sendData = st.getBytes();
DatagramPacket sendpac = new DatagramPacket(sendData,sendData.length,IPAddress,port);
soc.send(sendpac);}}
//Client
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.UnknownHostException;
import javax.swing.*;
public class Client extends JFrame implements ActionListener{
int port=5000;
public JFrame frame;
public JTextArea Room;
public JTextField msg;
public JTextArea Joiners;
DatagramSocket soc;
DatagramPacket pac;
byte[] receiveData = new byte[1024];
InetAddress IPAddress;
String Username="";
public ChatClient(String Username){
this.Username = Username;
Send();
try {
soc = new DatagramSocket();
pac = new DatagramPacket(receiveData, receiveData.length);
IPAddress = InetAddress.getByName("localhost");
send("$$"+Username);
} catch (IOException e) {
e.printStackTrace();
}
Thread th = new Thread(){
public void run(){
while(true){
try {
soc.receive(pac);
String st = new String(pac.getData()).substring(0, pac.getLength())+"\n";
Room.setText(st+Room.getText());
} catch (IOException e) {} }}};
th.start();
}
public void Send(){
this.frame = new JFrame("Chat Room");
this.frame.setSize(480 ,400);
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.setLayout(null);
JLabel lr=new JLabel("Chat room! Hello "+Username);
lr.setBounds(20, 10, 300, 25);
this.frame.add(lr);
this.Room=new JTextArea("");
this.Room.setBounds(20, 50, 420, 250);
this.Room.setEditable(false);
this.frame.add(Room);
JLabel lsd=new JLabel("Send");
lsd.setBounds(20, 325, 50, 25);
this.frame.add(lsd);
this.msg=new JTextField("");
this.msg.setBounds(100, 325, 200, 25);
this.frame.add(msg);
JButton OK=new JButton("Send");
OK.setBounds(320, 325, 80, 25);
OK.addActionListener(this);
this.frame.add(OK);
frame.setVisible(true);}
public void actionPerformed(ActionEvent e) {
if(!msg.getText().equals(" "))
{
try {
send(Username+" : "+msg.getText());
msg.setText("");
} catch (UnknownHostException e1) {
} catch (IOException e1) {}}}
public void send(String st) throws IOException{
byte[] sendData = st.getBytes();
DatagramPacket sendpac = new DatagramPacket(sendData,sendData.length,IPAddress,port);
soc.send(sendpac);}}
//Xuly ChatRoom
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
public class Login extends JFrame implements ActionListener{
TextField tfUser = new TextField();
TextField tfPass = new TextField();
Button btLogin = new Button("Login");
Button btCancel = new Button("Cancel");
public void Send1(){
this.setBounds(200, 300, 400, 200);
this.setLayout(new GridLayout(3,1));
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
p1.setLayout(new FlowLayout());
p1.add(new Label("User:
"));
p1.add(tfUser);
tfUser.setColumns(20);
p2.setLayout(new FlowLayout());
p2.add(new Label("Password:"));
p2.add(tfPass);
tfPass.setColumns(20);
p3.setLayout(new FlowLayout());
p3.add(btLogin);
p3.add(btCancel);
this.add(p1);
this.add(p2);
this.add(p3);
btLogin.addActionListener(this);
btCancel.addActionListener(this);}
public Login(){ Send1();}
public static void main(String []args){ new Login().setVisible(true);}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==btLogin){
if (!tfUser.getText().equals("")){
new ChatClient(tfUser.getText());
this.dispose();
}else{ tfUser.setText("Nhap lai user");
}}}}