자바 C/S 모드 채 팅 방 실현(말 병사 채 팅 방 프로그램 에 따라 최적화)
동시에 서버 를 추가 하면 모든 클 라 이언 트 에 게 상호작용 창 을 추가 하여 서버 가 모든 클 라 이언 트 와 상호작용 을 할 수 있 도록 합 니 다!
서버 코드
import java.net.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;
public class ChatServer extends JFrame {
JTextArea ta = new JTextArea();
ServerSocket server = null;
Collection cClient = new ArrayList();
public ChatServer(int port) throws Exception {
server = new ServerSocket(port);
add(ta, BorderLayout.CENTER);
setBounds(200, 200, 300, 450);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setVisible(true);
}
public void startServer() throws Exception {
while (true) {
Socket s = server.accept();
cClient.add(new ClientConn(s));
ta.append(s.getInetAddress().getHostName() + " " + " " + " "
+ s.getPort());
ta.append("
" + " : " + cClient.size() + "
");
}
}
class ClientConn extends Frame implements Runnable, ActionListener {
TextArea ta1 = null;
TextArea ta2 = null;
Button btn = null;
Socket s = null;
public ClientConn(Socket s) {
ta1 = new TextArea(3, 30);
ta2 = new TextArea(2, 15);
btn = new Button(" ");
this.setLayout(new BorderLayout());
this.add(ta1, BorderLayout.CENTER);
this.add(ta2, BorderLayout.SOUTH);
this.add(btn, BorderLayout.EAST);
this.setSize(300, 200);
this.setVisible(true);
this.setTitle("" + s.getInetAddress().getHostName() + " "
+ s.getPort());
this.s = s;
(new Thread(this)).start();
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
try {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(" :
" + ta2.getText() + "
");
ta1.append(" :
" + ta2.getText() + "
");
ta2.setText("");
} catch (IOException E) {
}
}
public void send(String str, String st) throws IOException {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(st + " :
" + str);
}
public void dispose() {
try {
// this.setVisible(false);
super.dispose();
ta.append(s.getInetAddress().getHostName() + " " + "
");
if (s != null)
s.close();
cClient.remove(this);
ta.append(" : " + cClient.size() + "
");
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
String st = s.getInetAddress().getHostName();
while (str != null && str.length() != 0) {
for (Iterator it = cClient.iterator(); it.hasNext();) {
ClientConn cc = (ClientConn) it.next();
if (this != cc) {
cc.send(str, st);
}
}
ta1.append(st + " :
" + str + "
");
str = dis.readUTF();
}
this.dispose();
} catch (Exception e) {
this.dispose();
}
}
}
public static void main(String[] args) throws Exception {
JFrame.setDefaultLookAndFeelDecorated(true);
ChatServer cs = new ChatServer(8888);
cs.startServer();
}
}
클 라 이언 트 코드
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JButton;
public class ChatClient extends JFrame {
JTextArea ta = new JTextArea(" !" + "
" + " ALT+ENTER
");
TextArea tf = new TextArea(3, 21);
JButton btn = new JButton(" ");
JPanel jp = new JPanel();
Socket s = null;
public ChatClient() throws Exception {
this.setLayout(new BorderLayout(10, 10));
this.add(ta, BorderLayout.CENTER);
jp.add(btn, BorderLayout.SOUTH);
this.add(tf, BorderLayout.SOUTH);
this.add(jp, BorderLayout.EAST);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
String sSend = tf.getText();
if (sSend.trim().length() == 0)
return;
ChatClient.this.send(sSend);
tf.setText("");
ta.append(" :" + "
");
ta.append(sSend + "
");
} catch (Exception e) {
e.printStackTrace();
}
}
});
btn.setMnemonic(KeyEvent.VK_ENTER);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setBounds(300, 300, 400, 500);
setVisible(true);
tf.requestFocus();
try {
s = new Socket("10.20.10.201", 8888);
} catch (Exception e) {
ta.append(" ! " + "
");
}
(new Thread(new ReceiveThread())).start();
}
public void send(String str) throws Exception {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
}
public void disconnect() throws Exception {
s.close();
}
public static void main(String[] args) throws Exception {
JFrame.setDefaultLookAndFeelDecorated(true);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ChatClient cc = new ChatClient();
String str = br.readLine();
while (str != null && str.length() != 0) {
cc.send(str);
str = br.readLine();
}
cc.disconnect();
}
class ReceiveThread implements Runnable {
public void run() {
if (s == null)
return;
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
while (str != null && str.length() != 0) {
ChatClient.this.ta.append(str + "
");
str = dis.readUTF();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.