网络编程之简单的多人聊天程序
2017-08-17 00:38
423 查看
服务器端
package net;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
//服务器端程序
public class TCPServer extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private ServerSocket ss = null;
private boolean bStart = false;
private JTextArea taContent = new JTextArea();
private int index = 0;
List<Client> clients = new ArrayList<Client>();
public void launchFrame() {
//Container con = this.getContentPane();
taContent.setEditable(false);
taContent.setBackground(Color.DARK_GRAY);
taContent.setForeground(Color.YELLOW);
this.add(taContent);
this.setSize(300, 350);
this.setLocation(400, 200);
this.setTitle("TCP Server");
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tcpMonitor();//调用监听器方法
}
//监听器方法
public void tcpMonitor() {
try {
ss = new ServerSocket(8888);
bStart = true;
} catch (IOException e) {
e.printStackTrace();
}
try {
while (bStart) {
index++;
Socket s = ss.accept();
Client c = new Client(s);
clients.add(c);
taContent.append(s.getInetAddress().getHostAddress()
+ " connected " + index + " clients\n");
new Thread(c).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) {
TCPServer ts = new TCPServer();
ts.launchFrame();
}
private class Client implements Runnable {
DataInputStream dis = null;
DataOutputStream dos = null;
Socket s = null;
boolean bStart = false;
Client(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
bStart = true;
}
//分发信息给每个客户端
public void sendToEveryClient(String str) {
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e) {
index--;
clients.remove(this);
taContent.append(s.getInetAddress().getHostAddress()
+ " exited " + index + " clients\n");
System.out.println("对方退出了!我从List里面去掉了!");
}
}
public void run() {
try {
while (bStart) {
String str = dis.readUTF();
System.out.println(str);
for (int i = 0; i < clients.size(); i++) {
Client c = clients.get(i);
c.sendToEveryClient(str);//群发消息当然要在循环 环境里
}
}
} catch (EOFException e) {
clients.remove(this);
taContent.append(s.getInetAddress().getHostAddress()
+ " exited " + clients.size() + " clients\n");
System.out.println("client closed");
} catch (SocketException e) {
System.out.println("client closed");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (s != null)
s.close();
if (dis != null)
dis.close();
if (dos != null)
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
客户端
package net;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
public class TCPClient extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
TextArea taContent = new TextArea();
JTextField tfTxt = new JTextField(20);
JButton send = new JButton("发送");
JButton connect = new JButton("连接");
JButton clear = new JButton("清空");
boolean live = false;
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
boolean bConnected = false;
Thread t = new Thread(new RecToServer());
public void launchFrame() {
taContent.setEditable(false);
p2.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 5));
p2.add(send);
p2.add(connect);
p2.add(clear);
Container con = this.getContentPane();
con.add(taContent, "North");
con.add(tfTxt, "Center");
con.add(p2, "South");
this.setSize(300, 350);
this.setLocation(400, 200);
this.setTitle("Chat Client");
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
connect.addActionListener(new Connect());
send.addActionListener(new SendMsg());
clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
taContent.setText("");
}
});
}
public void connectToServer() {
try {
s = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
bConnected = true;
} catch (BindException e) {
System.out.println("找不到指定的服务器");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void disConnect() {
try {
if (s != null) {
s.close();
}
if (dos != null) {
dos.close();
}
if (dis != null) {
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
TCPClient tc = new TCPClient();
tc.launchFrame();
}
private class Connect implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == "连接") {
connectToServer();
try {
t.start();
} catch (IllegalThreadStateException ex) {
}
connect.setText("断开连接");
} else if (e.getActionCommand() == "断开连接") {
disConnect();
connect.setText("连接");
}
}
}
private class SendMsg implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (connect.getActionCommand() == "连接") {
JOptionPane.showMessageDialog(TCPClient.this,
"没有找到指定的服务器", "错误提示", 1);
} else {
String str = tfTxt.getText();
tfTxt.setText("");
try {
dos.writeUTF(str);
dos.flush();
} catch (SocketException ex) {
System.out.println("没有找到指定的服务器");
JOptionPane.showMessageDialog(TCPClient.this,
"没有找到指定的服务器", "错误提示", 1);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
private class RecToServer implements Runnable {
public void run() {
try {
while (bConnected) {
String str = dis.readUTF();
// System.out.println(str);
taContent.append(str + "\n");
}
} catch (SocketException e) {
System.out.println("服务器已关闭");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package net;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
//服务器端程序
public class TCPServer extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private ServerSocket ss = null;
private boolean bStart = false;
private JTextArea taContent = new JTextArea();
private int index = 0;
List<Client> clients = new ArrayList<Client>();
public void launchFrame() {
//Container con = this.getContentPane();
taContent.setEditable(false);
taContent.setBackground(Color.DARK_GRAY);
taContent.setForeground(Color.YELLOW);
this.add(taContent);
this.setSize(300, 350);
this.setLocation(400, 200);
this.setTitle("TCP Server");
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tcpMonitor();//调用监听器方法
}
//监听器方法
public void tcpMonitor() {
try {
ss = new ServerSocket(8888);
bStart = true;
} catch (IOException e) {
e.printStackTrace();
}
try {
while (bStart) {
index++;
Socket s = ss.accept();
Client c = new Client(s);
clients.add(c);
taContent.append(s.getInetAddress().getHostAddress()
+ " connected " + index + " clients\n");
new Thread(c).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) {
TCPServer ts = new TCPServer();
ts.launchFrame();
}
private class Client implements Runnable {
DataInputStream dis = null;
DataOutputStream dos = null;
Socket s = null;
boolean bStart = false;
Client(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
bStart = true;
}
//分发信息给每个客户端
public void sendToEveryClient(String str) {
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e) {
index--;
clients.remove(this);
taContent.append(s.getInetAddress().getHostAddress()
+ " exited " + index + " clients\n");
System.out.println("对方退出了!我从List里面去掉了!");
}
}
public void run() {
try {
while (bStart) {
String str = dis.readUTF();
System.out.println(str);
for (int i = 0; i < clients.size(); i++) {
Client c = clients.get(i);
c.sendToEveryClient(str);//群发消息当然要在循环 环境里
}
}
} catch (EOFException e) {
clients.remove(this);
taContent.append(s.getInetAddress().getHostAddress()
+ " exited " + clients.size() + " clients\n");
System.out.println("client closed");
} catch (SocketException e) {
System.out.println("client closed");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (s != null)
s.close();
if (dis != null)
dis.close();
if (dos != null)
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
客户端
package net;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
public class TCPClient extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
TextArea taContent = new TextArea();
JTextField tfTxt = new JTextField(20);
JButton send = new JButton("发送");
JButton connect = new JButton("连接");
JButton clear = new JButton("清空");
boolean live = false;
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
boolean bConnected = false;
Thread t = new Thread(new RecToServer());
public void launchFrame() {
taContent.setEditable(false);
p2.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 5));
p2.add(send);
p2.add(connect);
p2.add(clear);
Container con = this.getContentPane();
con.add(taContent, "North");
con.add(tfTxt, "Center");
con.add(p2, "South");
this.setSize(300, 350);
this.setLocation(400, 200);
this.setTitle("Chat Client");
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
connect.addActionListener(new Connect());
send.addActionListener(new SendMsg());
clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
taContent.setText("");
}
});
}
public void connectToServer() {
try {
s = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
bConnected = true;
} catch (BindException e) {
System.out.println("找不到指定的服务器");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void disConnect() {
try {
if (s != null) {
s.close();
}
if (dos != null) {
dos.close();
}
if (dis != null) {
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
TCPClient tc = new TCPClient();
tc.launchFrame();
}
private class Connect implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == "连接") {
connectToServer();
try {
t.start();
} catch (IllegalThreadStateException ex) {
}
connect.setText("断开连接");
} else if (e.getActionCommand() == "断开连接") {
disConnect();
connect.setText("连接");
}
}
}
private class SendMsg implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (connect.getActionCommand() == "连接") {
JOptionPane.showMessageDialog(TCPClient.this,
"没有找到指定的服务器", "错误提示", 1);
} else {
String str = tfTxt.getText();
tfTxt.setText("");
try {
dos.writeUTF(str);
dos.flush();
} catch (SocketException ex) {
System.out.println("没有找到指定的服务器");
JOptionPane.showMessageDialog(TCPClient.this,
"没有找到指定的服务器", "错误提示", 1);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
private class RecToServer implements Runnable {
public void run() {
try {
while (bConnected) {
String str = dis.readUTF();
// System.out.println(str);
taContent.append(str + "\n");
}
} catch (SocketException e) {
System.out.println("服务器已关闭");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
相关文章推荐
- c#网络编程学习笔记02_Tcp编程(中)_简单的同步tcp聊天程序
- 【Java网络编程】UDP协议实例——简单的在线聊天程序
- 网络编程中简单的点对点聊天程序
- Java网络编程--简单聊天程序
- 黑马程序员_网络编程之简单的聊天程序
- 网络编程与多线程的应用--基于socket udp编写一个简单聊天程序
- Android 网络编程基础之简单聊天程序
- Java网络编程以及简单的聊天程序
- iPhone之网络编程初体验-简单的聊天程序
- Java网络编程以及简单的聊天程序
- 网络编程学习笔记二(实现一个基于简单TCP的用户注册程序)
- 网络通信(一):简单的聊天程序
- java 网络编程之UDP通信和简单的群聊程序
- linux网络编程之socket(三):最简单的回射客户/服务器程序、time_wait 状态
- java 网络编程五 (仿QQ聊天程序)
- Windows网络编程入门:简单的客户端和服务器通信程序调试
- 网络编程 CAsyncSocket类的应用实例 聊天程序 客户端代码
- Java网络编程:简单聊天机器人实现案例
- 【Java网络编程一】一个简单的c/s程序
- linux网络编程之socket(三):最简单的回射客户/服务器程序