22DH111684

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

22DH111684-Nguyễn Vũ Anh Khoa

Ví dụ 1:
Server:

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.nio.Buffer;

public class Server {


public static void main(String[] args) {
try{
// tao server socket vs port 1234
ServerSocket serverSocket = new ServerSocket(1234);
System.out.println("Server is running ");

//chap nhan yeu cau cua ket noi tu may khach


Socket clientSocket=serverSocket.accept();
System.out.println("Client connected");

//mo luong vao/ra de giao tiep vs may


BufferedReader in =new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter out=new
PrintWriter(clientSocket.getOutputStream(),true);

//Doc du lieu tu may khach


String clientmessage=in.readLine();
System.out.println("Client say: "+clientmessage);
out.println("server received your message");

//dong ket noi


clientSocket.close();
serverSocket.close();

}catch (IOException e){


e.printStackTrace();
}
}
}

Client:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.Buffer;

public class Client {


public static void main(String[] args) {
try {
// tao mot ket noi socket toi dia chi ip va cong cua may chu
Socket socket = new Socket("localhost",1234);

//mo luong vao/ra de giao tiep vs may chu


BufferedReader in= new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out=new PrintWriter(socket.getOutputStream(),true);

//gui thong diep


String message ="Tesing tcp client server";
out.println(message);

//nhan phan hoi tu server


String Servermessage =in.readLine();
System.out.println(Servermessage);

//dong ket noi


socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

Kết quả:
Ví dụ 2:

import java.util.HashMap;
import java.util.Map;

public class Hashmap {

public static void main(String[] args) {


//tao mot gia tri hashmap de luu tru cac cap khoa gia tri
Map<String,Integer> studentGrades =new HashMap<>();

// them cac cap khoa gia tri vao hashmap


studentGrades.put("Khoa", 95);
studentGrades.put("jack", 92);
studentGrades.put("bell", 69);
studentGrades.put("Simmon", 90);

//truy cap gia tri dua tren khoa


int khoa= studentGrades.get("Khoa");
System.out.println("diem so cua khoa : "+ khoa);

//xoa mot cap gia tri


studentGrades.remove("jack");

//kiem tra hashmap co chua mot khoa cu the hay ko


boolean containsBob = studentGrades.containsKey("bell");
System.out.println("Contains bell? "+containsBob);

//lay so luong cap khoa gia tri trong hashmap


int size = studentGrades.size();
System.out.println("number of students: "+ size);

//lap qua tat ca cac cap khoa gia tri trong hashmap
for(Map.Entry<String,Integer> entry: studentGrades.entrySet()){
String studentName = entry.getKey();
int grade =entry.getValue();
System.out.println(studentName + " "+grade);
}

}
}

Kết quả:

Ví dụ 3:

import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
public class MySQLExample {
public static void main(String[] args) throws SQLException{
String url="jdbc:MySQL://localhost:3306/java_user_database";
String Username="root";
String Password="";

try{
// neu su dung java<9
Class.forName("com.mysql.cj.jdbc.Driver");

//khoi tao doi tuong connection


Connection conn =DriverManager.getConnection(url, Username,
Password);
System.out.println("Connected!! ");

//tao doi tuong statement


Statement stmt = (Statement) conn.createStatement();

//thuc hien truy van sql


String sql="SELECT * FROM user";
ResultSet rs=((java.sql.Statement) stmt).executeQuery(sql);
while (rs.next()) {
int id =rs.getInt("id");

String name =rs.getString("fullname");


String email =rs.getString("email");
System.out.println("ID: "+id+"name: "+name +"email: "+email);

}
}catch (Exception e){
System.out.println("Cannot connect to sql ");
e.printStackTrace();
}
}
}

Bài tập 1:
Server:

import java.io.*;
import java.net.*;
import java.util.HashMap;

public class Server {


private static HashMap<String, String> accountDatabase = new HashMap<>();

public static void main(String[] args) {


try {
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server is running...");

while (true) {
Socket clientSocket = serverSocket.accept();
new ClientHandler(clientSocket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}

private static class ClientHandler extends Thread {


private final Socket clientSocket;
public ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}

@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new
PrintWriter(clientSocket.getOutputStream(), true);

String username = in.readLine();


String password = in.readLine();

if (accountDatabase.containsKey(username)) {
out.println("Username already exists.");
} else if (password.length() <= 8) {
out.println("Password must be longer than 8 characters.");
} else {
accountDatabase.put(username, password);
out.println("Account registered successfully.");
}

clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Client:

import java.io.*;

import java.net.*;
import java.util.Scanner;

public class Client {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 12345);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// Gửi thông tin đăng ký tài khoản


Scanner nhapusername=new Scanner(System.in);
Scanner nhappassword=new Scanner(System.in);

System.out.println("nhap username: ");


String username=nhapusername.nextLine();

System.out.println("nhap password: ");


String password=nhappassword.nextLine();

out.println(username);
out.println(password);

// Nhận thông báo từ Server


String response = in.readLine();
System.out.println("Server response: " + response);

socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Kết quả:

Bài tập 2:
Server:

import java.io.*;
import java.net.*;
import java.util.Random;

public class Server1 {


public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server is running...");

int secretNumber = new Random().nextInt(100) + 1;


int guessCount = 0;

while (true) {
Socket clientSocket = serverSocket.accept();
new ClientHandler(clientSocket, secretNumber,
guessCount).start();
guessCount++;
}
} catch (IOException e) {
e.printStackTrace();
}
}

private static class ClientHandler extends Thread {


private final Socket clientSocket;
private final int secretNumber;
private int guessCount;

public ClientHandler(Socket clientSocket, int secretNumber, int


guessCount) {
this.clientSocket = clientSocket;
this.secretNumber = secretNumber;
this.guessCount = guessCount;
}

@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new
PrintWriter(clientSocket.getOutputStream(), true);

out.println("Welcome to Number Guessing Game!");


out.println("Guess a number between 1 and 100:");

while (true) {
String guessStr = in.readLine();
int guess = Integer.parseInt(guessStr);
if (guess == secretNumber) {
out.println("Congratulations! You guessed the correct
number.");
out.println("Total guesses: " + guessCount);
break;
} else if (guess < secretNumber) {
out.println("Try a higher number.");
} else {
out.println("Try a lower number.");
}
}

clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Client:

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Client1 {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 12345);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in);

System.out.println(in.readLine()); // Welcome message

while (true) {
System.out.print("Your guess: ");
int guess = scanner.nextInt();
out.println(guess);

String response = in.readLine();


System.out.println(response);

if (response.contains("Congratulations")) {
break;
}
}

socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Kết quả:

You might also like