1. Trang chủ
  2. » Công Nghệ Thông Tin

Đề Lập trình mạng

18 1,5K 22

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 18
Dung lượng 75 KB
File đính kèm Java_LTM.rar (149 KB)

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

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.DataOutput

Trang 1

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;

Trang 2

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<this.sv.cls.size();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

Trang 3

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);

Trang 4

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;

Trang 5

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);

Trang 6

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);

Trang 7

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());

Trang 8

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<s.length();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<s.length();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<s.length();i++) {

if(s.charAt(i)==' ' && s.charAt(i+1)!=' ' && s.charAt(i+1)!='\0') {count++;}}

Trang 9

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ử +, -, (, )

- 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();

Trang 10

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;

Trang 11

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;}

Trang 12

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();

Trang 13

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;

Trang 14

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<IP.size();i++)

send(st,IP.get(i),port.get(i)); }} catch (IOException e) {} } public void send(String st, InetAddress IPAddress,int port) throws IOException{

Trang 15

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(){

Ngày đăng: 06/04/2016, 09:17

TỪ KHÓA LIÊN QUAN

w