Professional Documents
Culture Documents
1. Form ClientChat
txtPort btnConnect
btnClose
txtSend btnSend
taServer
import java.awt.Font;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public ClientChat() {
initComponents();
setLocationRelativeTo(null);
tdClient = new Thread(new Runnable() {
public void run() {
connectServer(Integer.parseInt(txtPort.getText()));
while (true) {
String s;
try {
s = inFromServer.readLine();
if (s!=null) {
taServer.append(s+"\n");
}
} catch (IOException ex) { };
}
}
});
}
public boolean connectServer(int port) {
try {
clientSocket = new Socket("localhost", port);
inFromServer = new BufferedReader( new InputStreamReader(clientSocket.getInputStream()));
3. Form Server
txtPort
btnClose
btnStart
taClient
txtSend
btnSend
4. Code phía Server
import java.awt.Font;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.stage.FileChooser;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
public ServerChat() {
initComponents();
this.setLocationRelativeTo(null);
tdServer = new Thread(new Runnable() {
public void run() {
connectClient(Integer.parseInt(txtPort.getText()));
while (true) {
if (inFromClient!=null)
try {
String s = inFromClient.readLine();
if (s!=null)
taClient.append(s+"\n");
} catch (IOException ex) {}
}
}
});
}
private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {
btnStart.setEnabled(false);
txtSend.grabFocus();
tdServer.start(); // chạy Server
}
5. Thực hiện
- Chạy ứng dụng Server : gõ số port kết nối ( 1234 ), nhắp nút Start
- Chạy ứng dụng Client : gõ số port giống với port Serve , nhắp Connect
- Bắt đầu chat