You are on page 1of 17

LP TRNH SOCKET VI JAVA

Ngi vit: Hong Tun Hng K50CD H Cng Ngh - HQGHN Email: hunght@fpt.vn

Ni dung:
I. Khi qut v Socket. II. Socket l g? III. Lp trnh Socket bng Java. Ci t Java. Cc hm thao tc trn Java: M mt socket bn pha server. M mt socket bn pha client. To i tng Input Stream. To i tng Output Stream. ng kt ni. IV. Mt s v d. V d 1: ng dng server-client n gin, server s gi thng ip cho client l: Hello World. V d 2: server v client s ni chuyn vi nhau theo mt protocol. V d 3: mt server ni chuyn c vi nhiu client.

I. KHI QUT V SOCKET Nh chng ta bit kt ni URLs v URL cung cp cho chng ta mt c cu truy xut vo cc ti nguyn trn Internet mt mc tng i cao, nhng i khi chng trnh ca chng ta li yu cu mt giao tip tng mng mc thp. V d khi chng ta vit mt ng dng clientserver. Trong mt ng dng client-server th pha server s cung cp mt s dch v, nh: x l c s d liu, cc yu cu bn pha client a ra, sau s gi li cho pha client. S giao tip nh vy gi l tin cy bi v d liu s khng b mt mt, sai lch trong qu trnh truyn, server gi cho client thng ip g th pha client s nhn c thng ip nguyn nh vy. Giao thc TCP s cung cp cho chng ta mt cch thc truyn tin cy. c th ni chuyn c trn TCP th chng trnh client v chng trnh server phi thip lp mt ng truyn, v mi chng trnh s phi kt ni li vi socket l im cui kt ni, client v server mun ni chuyn vi nhau th s phi thng qua socket, mi thng ip s phi i qua socket. Chng ta c mng tng socket y l mt ci ca mi ngi mun i ra hay i vo u phi thng qua ci ca ny. II. SOCKET L G? Mt socket l mt im cui ca thng tin hai chiu lin kt gia hai chng trnh ang chy trn mng. Nhng lp socket c dng i din cho kt ni gia mt chng trnh client v mt chng trnh server. Trong Java gi Java.net cung cp hai lp Socket v ServerSocket thc hin kt ni gia client v server. Thng thng th server s chy trn mt my c bit v c mt socket gii hn trong mt Port number c bit. Pha client: client c bit hostname ca my m server ang chy v port number m server ang lng nghe. to mt yu cu kt 2

ni client s th hn gp server trn my ca server thng qua port number. Client cng cn xc nh chnh n vi server thng qua local port number.

Nu mi th tt p th server s ng kt ni. khi ng kt ni th server s to ra mt socket mi ni chuyn vi client v cng to ra mt socket khc tip tc lng nghe.

Sau y l hng dn lp trnh socket trong Java. III. LP TRNH SOCKET BNG JAVA. Ci t Java. Chng ta s ci t mt b JDK v mt mi trng pht trin. ci t JDK chng ta lm nh sau: Download JDK theo a ch: https://sdlc6d.sun.com/ECom/EComActionServlet/DownloadPage:~:com.s un.sunit.sdlc.content.DownloadPageInfo;jsessionid=8768F4A376837F76F 224EEF98B2103B1;jsessionid=8768F4A376837F76F224EEF98B2103B1 Trong s c cc bn dnh cho Windows v Linux. ci t mt mi trng pht trin( y ta dng Netbean) a ch download: https://sdlc2b.sun.com/ECom/EComActionServlet/DownloadPage:~:com.s un.sunit.sdlc.content.DownloadPageInfo;jsessionid=FB9B3F6AB51ADD29

6B99E6C8A54F69B1;jsessionid=FB9B3F6AB51ADD296B99E6C8A54F69 B1 Trong s c cc bn dnh cho Windows v Linux. Cc hm thao tc trn Socket: u tin chng trnh pha server phi chy v lng nghe trn mt cng no ch pha client kt ni ti, nu kt ni thnh cng th c hai pha u c hai th hin ca lp socket v d liu s c truyn qua hai lp socket ny. Thng thng trong mt chng trnh s c cc bc c bn sau: 1. M mt socket. 2. M mt input stream v output stream ti socket. 3. c v vit ti stream thng qua giao thc ca server. 4. ng Stream. 5. ng socket. Pha server m mt socket bng cch sau: ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(PortNumber); } catch (IOException e) { System.err.println("Could not listen on port: "+ PortNumber); System.exit(1); } Pha server cn phi khi to i tng ca lp ServerSocket lng nghe v chp nhn kt ni t client. Trong PortNumber l s hiu cng server m ra lng nghe (ch : cc cng t 0-1023 c s dng cho cc ng dng c bit nh: HTTP, FTP, SMTP nn chng ta ch chn cc cng t 1024 tr i). Socket clientSocket = null; 4

try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } Pha client m socket bng cch sau: Socket MySocket = null; try { MySocket = new Socket("Machine name", PortNumber); } catch (UnknownHostException e) { System.err.println("Don't know about host: "); System.exit(1); } Trong Machine name l tn (hoc a ch IP) ca my tnh server, PortNumber l s hiu cng m server ang lng nghe. Sau khi m c socket cho client v server c th gi v nhn thng ip vi nhau th chng ta phi khi to i tng Input Stream v Output Stream. To i tng Input Stream Pha client phi s dng lp BufferedReader to input vi mc ch nhn thng ip t server. BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader( MySocket.getInputStream())); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: local host."); 5

System.exit(1); } Pha server cng s dng lp BufferedReader nhn thng ip tng t nh pha client. To i tng Output Stream. Pha client s s dng lp PrintWriter gi thng ip qua cho server. PrintWriter out = null; try { out = new PrintWriter(MySocket.getOutputStream(), true); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: local host."); System.exit(1); } Bn pha server mun gi thng ip cho client th cng lm tng t nh bn client hng dn trn. ng kt ni. Sau khi vic gi v nhn thng ip gia client v server thc hin xong th ta s phi ngt kt ni, ch : phi ng input v output stream trc khi ng socket. Pha client: Try { Out.close(); In.close(); MySocket.close(); } catch (IOException e) { System.out.println(e); } 6

Pha server: Try { Out.close(); In.close(); clientSocket.close(); serverSocket.close(); } catch (IOException e) { System.out.println(e); } IV. Mt s v d: 1. v d 1: To mt project trong c 2 file l: Server.java v Client.java, y l mt v d n gin ban u minh ha mt ng dng server/client. Server s m cng 1234 cho client kt ni ti, sau khi kt ni thnh cng th server s gi cho client thng ip l: Hello World sau khi client nhn c thng ip ny th s ng kt ni li. M ngun ca Server.java:
import java.net.*; import java.io.*; public class Server { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; String data= "Hello World"; try { serverSocket = new ServerSocket(1234); System.out.println("Server listening"); } catch (IOException e) { System.err.println("Could not listen on port: 1234."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept();

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); out.print(data); out.close(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } clientSocket.close(); serverSocket.close();

} }

u tin i tng ServerSocket c khi to lng nghe cng 1234. Sau khi khi to th i tng socket s dng phng thc accept() i client kt ni ti. Khi vic kt ni thnh cng ta s to i tng output stream gi thng ip cho client, thng ip s c gi sang cho client thng qua phng thc Print(). y l m ngun ca Client.java:
import java.io.*; import java.net.*; public class Client { public static void main(String[] args) throws IOException { Socket MySocket = null; BufferedReader in = null; try { MySocket = new Socket("localhost", 1234); in = new BufferedReader(new InputStreamReader(MySocket.getInputStream())); String fromServer= in.readLine(); System.out.print(fromServer); in.close(); } catch (UnknownHostException e) { System.err.println("Don't know about host:"); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to:"); System.exit(1); } MySocket.close();

Mt i tng socket c to ra kt ni vi server. y client s kt ni vi server qua a ch localhost cng 1234- cng m server m v ang lng nghe. Sau s tip tc to i tng input stream nhn thng ip t server, khi nhn c thng ip t server th client s in thng ip ra v ng kt ni li. 2. v d 2: Bn trn ch l v d n gin minh ha cho ng dng server/client. Sau y s l mt v d khc trong server v client s ni chuyn vi nhau nhiu hn, server s to ra mt protocol ni chuyn, client s phi tun th theo protocol . To mt project c cha 3 file l: ChamSocServer.java, Trong ChamSocClient.java, ChamSocProtocol.java.

ChamSocProtocol.java s quy nh quy tc ni chuyn gia client v server. Trong v d ny th ta gii nh y l mt h thng tr li chm sc khch hng ca mt cng ty no . Khi kt ni thnh cng server s gi li cho client thng ip l: Xin chao mung cac ban den voi dich vu cham soc khach hang!! tc l kt ni thnh cng, khi client s bt u a ra cc yu cu server tr li. y quy nh l client ch c hi hai cu hi v sau phi tr li mt cu v phi theo ng th t sau: cu 1: "day la dv gi?", sau khi c server tr li th client s phi tip tc hi tip cu th 2 l: "la gi?" khi server s tr li bn v hi li bn mt cu: Ban co muon chuyen den dv khac? (y/n) nu client tr li y th server s chuyn n dch v tip theo v client s li thc hin li qu trnh nh trn, cn nu client tr li l n th qu trnh ni chuyn kt thc v ng kt ni li. Sau y l m ngun chng trnh:

M ngun file ChamSocServer.java:


import java.net.*; import java.io.*; public class ChamSocServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(1234); System.out.println("Server listening"); } catch (IOException e) { System.err.println("Could not listen on port: 1234."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader( clientSocket.getInputStream())); String inputLine, outputLine; ChamSocProtocol kkp = new ChamSocProtocol(); outputLine = kkp.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.println(outputLine); if (outputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); } }

M ngun file ChamSocProtocol.java:


import java.net.*; import java.io.*;

10

public class ChamSocProtocol private static final int private static final int private static final int private static final int

{ WAITING = 0; SENT = 1; SENTCLUE = 2; ANOTHER = 3;

private static final int NUMJOKES = 5; private int state = WAITING; private int count = 0; private String[] clues = { "Gioi thieu", "Cac san pham", "Cac tinh nang", "Tu van", "Thong tin lien lac" }; private String[] answers = { "Se gioi thieu ve cong ty cua chung toi!", "Trung bay mot so san pham cua cong ty!", "Neu nhung tinh nang noi bat cua cac san pham!", "Chung toi se tu van cho cac ban nhung san pham phu hop voi cac ban!", "O day se la dia chi lien lac cua cong ty chung toi!" }; public String processInput(String theInput) { String theOutput = null; if (state == WAITING) { theOutput = "Xin chao mung cac ban den voi dich vu cham soc khach hang!!"; state = SENT; } else if (state == SENT) { if (theInput.equalsIgnoreCase("day la dv gi?")) { theOutput = clues[count]; state = SENTCLUE; } else { theOutput = "Ban phai hoi la: \"day la dv gi?\"! " + "Try again."; } } else if (state == SENTCLUE) { if (theInput.equalsIgnoreCase("la gi?")) { theOutput = answers[count] + " Ban co muon chuyen den dv khac? (y/n)"; state = ANOTHER; } else { theOutput = "Ban phai hoi la: \"la gi?\"! " + "Try again."; state = SENTCLUE; } } else if (state == ANOTHER) { if (theInput.equalsIgnoreCase("y")) { theOutput = "Xin chao ban den voi DV tiep theo"; if (count == (NUMJOKES - 1)) count = 0; else

11

count++; state = SENT; } else { theOutput = "Bye."; state = WAITING; } } return theOutput; } }

y l quy tc ni chuyn gia client v server nh ni trn. M ngun file ChamSocClient.java:

import java.io.*; import java.net.*; public class ChamSocClient { public static void main(String[] args) throws IOException { Socket csSocket = null; PrintWriter out = null; BufferedReader in = null; try { csSocket = new Socket("localhost", 1234); out = new PrintWriter(csSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(csSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: localhost."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: localhost."); System.exit(1); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String fromServer; String fromUser; while ((fromServer = in.readLine()) != null) { System.out.println("Server: " + fromServer); if (fromServer.equals("Bye.")) break; fromUser = stdIn.readLine(); if (fromUser != null) { System.out.println("Client: " + fromUser); out.println(fromUser);

12

} }

out.close(); in.close(); stdIn.close(); csSocket.close();

Trn y l mt chng trnh ng dng client/server kh in hnh, trong v d trn ch l mt server phc v mt client m thi, tuy nhin trong thc t li khng phi l mt server phc v mt client na m l mt server phc v nhiu client. c th lm c iu th trong Java c c ch a lung, tc l mi khi c mt yu cu kt ni t mt client no th server s to ra mt lung kt ni vi client . Nh vy th trong cng mt lc s c th c rt nhiu client cng kt ni n mt server. Sau y s l m ngun ca chng trnh: 3. V d 3: M ngun file ChamSocServer.java:
import java.net.*; import java.io.*; public class ChamSocServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; boolean listening = true; try { serverSocket = new ServerSocket(1234); System.out.println("Server is listening"); } catch (IOException e) { System.err.println("Could not listen on port: 1234."); System.exit(-1); } while (listening) new ServerThread(serverSocket.accept()).start(); } } serverSocket.close();

13

M ngun file ServerThread.java:


import java.net.*; import java.io.*; public class ServerThread extends Thread { private Socket socket = null; public ServerThread(Socket socket) { super("ServerThread"); this.socket = socket; } public void run() { try { PrintWriter out = new PrintWriter(socket.getOutputStream(), BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream())); String inputLine, outputLine; Protocol cs = new Protocol(); outputLine = cs.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = cs.processInput(inputLine); out.println(outputLine); if (outputLine.equals("Bye")) break; } out.close(); in.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }

true);

M ngun file Protocol.java:


import java.net.*; import java.io.*; public class Protocol { private static final private static final private static final private static final

int int int int

WAITING = 0; SENT = 1; SENTCLUE = 2; ANOTHER = 3;

private static final int NUMJOKES = 5;

14

private int state = WAITING; private int count = 0; private String[] clues = { "Gioi thieu", "Cac san pham", "Cac tinh nang", "Tu van", "Thong tin lien lac" }; private String[] answers = { "Se gioi thieu ve cong ty cua chung toi!", "Trung bay mot so san pham cua cong ty!", "Neu nhung tinh nang noi bat cua cac san pham!", "Chung toi se tu van cho cac ban nhung san pham phu hop voi cac ban!", "O day se la dia chi lien lac cua cong ty chung toi!" }; public String processInput(String theInput) { String theOutput = null; if (state == WAITING) { theOutput = "Xin chao mung cac ban den voi dich vu cham soc khach hang!!"; state = SENT; } else if (state == SENT) { if (theInput.equalsIgnoreCase("day la dv gi?")) { theOutput = clues[count]; state = SENTCLUE; } else { theOutput = "Ban phai hoi la: \"day la dv gi?\"! " + "Try again."; } } else if (state == SENTCLUE) { if (theInput.equalsIgnoreCase("la gi?")) { theOutput = answers[count] + " Ban co muon chuyen den dv khac? (y/n)"; state = ANOTHER; } else { theOutput = "Ban phai hoi la: \"la gi?\"! " + "Try again."; state = SENTCLUE; } } else if (state == ANOTHER) { if (theInput.equalsIgnoreCase("y")) { theOutput = "Xin chao ban den voi DV tiep theo"; if (count == (NUMJOKES - 1)) count = 0; else count++; state = SENT; } else { theOutput = "Bye."; state = WAITING; } } return theOutput; }

15

M ngun file ChamSocClient.java:


import java.io.*; import java.net.*; public class ChamSocClient { public static void main(String[] args) throws IOException { Socket csSocket = null; PrintWriter out = null; BufferedReader in = null; try { csSocket = new Socket("localhost", 1234); out = new PrintWriter(csSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(csSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: localhost."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: localhost."); System.exit(1); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String fromServer; String fromUser; while ((fromServer = in.readLine()) != null) { System.out.println("Server: " + fromServer); if (fromServer.equals("Bye.")) break; fromUser = stdIn.readLine(); if (fromUser != null) { System.out.println("Client: " + fromUser); out.println(fromUser); } }

} }

out.close(); in.close(); stdIn.close(); csSocket.close();

Hy vng c n y mi ngi c th hiu mt phn no v Socket, v c th t vit c mt s ng dng client-server. 16

Good Luck!

17

You might also like