Professional Documents
Culture Documents
Thuc Hanh TCP Socket PDF
Thuc Hanh TCP Socket PDF
import java.io.DataOutputStream;
import java.net.*;
import java.util.Date;
public class TimeServer {
public static void main(String[] args) throws Exception
{
ServerSocket server = new ServerSocket(7000);
System.out.println("Server is started");
while(true) {
Socket socket = server.accept();
DataOutputStream dos = new
DataOutputStream(socket.getOutputStream());
String time = new Date().toString();
dos.writeUTF("Server tra lai ngay gio="+time);
socket.close();
}
}
}
b. Client
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
}
}
2. Thay i chng trnh bi 1 sao cho c mi giy chng trnh Server tr v cho client
thi gian mi. Chng trnh Server c kh nng phc v nhiu client (chng trnh Multi-
threading).
3. T chng trnh trn to mt ng h in t pha client v cho php ngi dng chn
thnh ph. Thi gian cp nht c gi v t Server sau mi giy (chng trnh Multi-
threading).
4. Chy chng trnh sau:
a. Server
import java.io.*;
import java.util.*;
import java.net.*;
/*Chuong trinh chat don gian
Server nhan message tu Client
*/
public class SimpleChatServer {
public static void main(String[] args) throws Exception
{
ServerSocket server = new ServerSocket(7000);
System.out.println("Server is started");
while(true) {
//nhan du lieu tu client
String st = din.readUTF();
System.out.println(st);
System.out.print("Server: ");
String msg=kb.nextLine();
dos.writeUTF("Server: "+msg);
dos.flush();
kb=kb.reset();
}
//socket.close();
}
}
b. Client
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.*;
while(true) {
System.out.print("Client: ");
String msg=kb.nextLine();
dos.writeUTF("Client: "+msg);
dos.flush();
kb = kb.reset();
}
5. Da vo bi 4, vit chng trnh client cho php ngi dng nhp vo 2 s thc v mt
php ton (+, -, *, /) ri gi n chng trnh Server. Chng trnh Server thc hin tnh
ton kt qu da vo php ton tng ng v tr kt qu cho chng trnh Client. Mi ln
tnh ton c, server u lu kt qu xung CSDL.
6. Vit chng trnh chat cho php cc client gi d liu nhp t bn phm qua li. (S dng
Multi-threading).
7. Pht trin bi 6, chng trnh server c kt ni CSDL qun l accounts ngi dng.