java socket聊天

来源:互联网 发布:反对网络暴力的口号 编辑:程序博客网 时间:2024/05/19 16:32

Server端:

package com.util.lqbz.socket.lt;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintStream;import java.net.ServerSocket;import java.net.Socket;import java.util.StringTokenizer;import java.util.Vector;/** * 服务器端编码 * Yanxinyu */public class Server {static int port = 5566;//端口号static Vector<Client> clients = new Vector<Client>(10);//存储连接客户信息static ServerSocket server = null; //建立服务器socketstatic Socket socket = null; //套接字连接/** * Constructs */public Server() {try {System.out.println("Server start...");server  = new ServerSocket(port); //初始化服务器套接字while (true) {socket = server.accept(); //等待连接System.out.println(socket.getInetAddress()+"连接\n");//得到客户机地址Client client = new Client(socket); //实例化一个客户线程(其中线程Client中有Socket,这里的的Socket只是起个过度作用)//clients.add(client);//增加客户线程到向量中client.start();//启动线程notifyChatRoom(); //监视聊天室连接变化}} catch (Exception ex) {ex.printStackTrace();//输出出错信息}}/** * 监视客户端线程 */public static void notifyChatRoom() { //监视客户端线程StringBuffer newUser = new StringBuffer("newUser");for (int i = 0; i < clients.size(); i++) {Client c = (Client)clients.elementAt(i);newUser.append(":"+c.name); //客户端姓名字符串}sendClients(newUser);//发送信息到客户端}public static void sendClients(StringBuffer message) {for (int i= 0 ; i < clients.size(); i++) {Client client = (Client)clients.elementAt(i);//分别得到每个客户端的连接client.send(message);//发送信息}}/** * 关闭所有连接 */public void closeAll() { //关闭所有连接while (clients.size() > 0 ) { //遍历整个VectorClient client = (Client) clients.firstElement(); //得到一个客户端try {client.socket.close();} catch(IOException ex) {ex.printStackTrace(); // 输出错误信息}clients.removeElement(client); //移出客户端}}public static void disconnect(Client c) {// 断开客户端try {System.err.println(c.ip+"断开连接\n");} catch (Exception ex) {ex.printStackTrace();}clients.removeElement(c);c.socket = null;}/** * main方法 * @param args */public static void main(String[] args) {new Server();}class Client extends Thread {Socket socket;//连接端口String name ;//用户姓名String ip; //客户端ip地址BufferedReader reader;//输入流PrintStream ps;//输出流public Client(Socket s) {socket = s;try {reader = new BufferedReader(new InputStreamReader(s.getInputStream()));//得到输入流ps = new PrintStream(s.getOutputStream());//得到输出流String info = reader.readLine();//读取接收到的信息StringTokenizer stinfo = new StringTokenizer(info,":"); //分解字符串String head = stinfo.nextToken(); //获取关键字System.out.println(stinfo.toString());System.out.println(head);if (stinfo.hasMoreTokens()){name = stinfo.nextToken() ;//获取用户名}if (stinfo.hasMoreTokens()) {ip = stinfo.nextToken(); //获取IP地址}} catch (IOException ex) {ex.printStackTrace();}System.out.println(name);System.out.println(ip);}public void send (StringBuffer msg) {ps.println(msg); //输出信息ps.flush();}public void run() {while (true) {String line = null;try {line = reader.readLine();System.out.println("line:"+line);} catch (IOException ex) {ex.printStackTrace(); //输出错误信息Server.disconnect(this);//断开连接Server.notifyChatRoom();//更新信息return ;}if (line == null) { //客户离开Server.disconnect(this);Server.notifyChatRoom();return ;}StringTokenizer st = new StringTokenizer(line,":");//分解字符串String keyword = st.nextToken();if (keyword.equals("MSG")) { //发送来的聊天信息StringBuffer msg = new StringBuffer("MSG:");msg.append(name); //在信息上增加用户名msg.append(st.nextToken("\0\n"));Server.sendClients(msg);//发送聊天语句到各个客户端System.out.println(msg);} else if (keyword.equals("quit")) { //退出命令Server.disconnect(this); //断开连接Server.notifyChatRoom(); //刷新信息}}}}}

Client端:

package com.util.lqbz.socket.lt;import java.awt.BorderLayout;import java.awt.Button;import java.awt.Color;import java.awt.Font;import java.awt.Label;import java.awt.TextArea;import java.awt.TextField;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintStream;import java.io.UnsupportedEncodingException;import java.net.InetAddress;import java.net.Socket;import java.util.StringTokenizer;import javax.swing.JFrame;import javax.swing.JOptionPane;import javax.swing.JPanel;/** * 基于Socket网络聊天程序 客户端编码 * Yanxinyu*/public class Client extends JFrame  implements ActionListener{TextField tfName = new TextField(15);//姓名输入文本域Button btConnect = new Button("Connection");//连接按钮Button btDisconnect = new Button("discon");//断开连接按钮TextArea tfChat = new TextArea(8,27);//显示聊天信息文本域Button btSend = new Button("send");TextField tfMessage = new TextField(30);//聊天输入java.awt.List list1  = new java.awt.List(9);//显示在线用户信息 Socket socket = null;//连接端口PrintStream ps = null;//输出流Listen listen = null;//监听线程类class Listen extends Thread {BufferedReader reader;PrintStream ps;String cname;Socket socket;Client Client;public Listen(Client client,String name,Socket socket) {try {this.Client = client; this.socket = socket; this.cname = name; reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); ps = new PrintStream(socket.getOutputStream());} catch (IOException e) {e.printStackTrace();}}public void run() {while (true) {String line=null ;try {line = reader.readLine(); //读取数据流System.out.println("客户端:"+line);}catch (IOException ex) {ex.printStackTrace();ps.println("quit");; //断开连接return;}StringTokenizer stinfo = new StringTokenizer(line,":"); //分解字符串String keyword = stinfo.nextToken();if (keyword.equals("MSG")) {Client.tfChat.append(line+"\n");}else if (keyword.equals("newUser")){Client.list1.clear();Client.list1.add("users", 0);int i = 1;while (stinfo.hasMoreTokens()) {Client.list1.add(stinfo.nextToken(), i++);}}   }  }}public void actionPerformed(ActionEvent e) {try{if(e.getSource()==btConnect) { //点击连接按钮if (socket == null) {socket = new Socket(InetAddress.getLocalHost(),5566);//实例化一个套接字ps = new PrintStream(socket.getOutputStream());//获取输出流,写入信息StringBuffer info = new StringBuffer("info:");String userinfo = tfName.getText()+":"+InetAddress.getLocalHost().toString();ps.println(info.append(userinfo));//输出信息ps.flush();listen = new Listen(this,tfName.getText(),socket);listen.start();}} else if (e.getSource() == btDisconnect) { //点击断开连接按钮disconnect();} else if (e.getSource() == btSend) { //点击发送按钮if (socket != null) {StringBuffer msg = new StringBuffer("MSG:");String msgtxt = new String(tfMessage.getText());ps.println(msg.append(msgtxt));//发送信息ps.flush();} else {JOptionPane.showMessageDialog(this, "请先连接!", "提示", 1);}}} catch (Exception ex) {ex.printStackTrace();//输出错误信息}}public void disconnect() { //断开连接方法if (socket != null) {ps.println("quit");//发送信息ps.flush();socket = null;tfName.setText("");}}public Client(Socket socket) throws UnsupportedEncodingException {this.setLayout(new BorderLayout());//this.setFont(new Font("宋体", 0, 8));JPanel panel1 = new JPanel();Label label = new Label("Name");panel1.setBackground(Color.orange);panel1.add(label);panel1.add(tfName);panel1.add(btConnect);panel1.add(btDisconnect);this.add(panel1,BorderLayout.NORTH);JPanel panel2 = new JPanel();panel2.add(tfChat);panel2.add(list1);this.add(panel2,BorderLayout.CENTER);JPanel panel3 = new JPanel();Label label2 = new Label("Message info");panel3.add(label2);panel3.add(tfMessage);panel3.add(btSend);this.add(panel3,BorderLayout.SOUTH);this.setBounds(50,50,400,350);this.setVisible(true);btConnect.addActionListener(this);btDisconnect.addActionListener(this);btSend.addActionListener(this);}/** * @param args * @throws UnsupportedEncodingException  */public static void main(String[] args) throws UnsupportedEncodingException {Client client = new Client(new Socket());System.out.println(client.socket);}}


原创粉丝点击