Java基础聊天室基于Swing socket通信

Java基础聊天室socket serve基于Swing

  • 使用java swing包进行ui设计,通过socket通信,实现服务器和客户端的连接互发消息并通过JTextArea显示出来。
    • 话不多说 直接贴代码

新人第一次发帖有点紧张,该项目为java课设,小东西可供大家参考,转载

使用java swing包进行ui设计,通过socket通信,实现服务器和客户端的连接互发消息并通过JTextArea显示出来。

图片: Java基础聊天室基于Swing socket通信_第1张图片Java基础聊天室基于Swing socket通信_第2张图片Java基础聊天室基于Swing socket通信_第3张图片Java基础聊天室基于Swing socket通信_第4张图片

话不多说 直接贴代码

client.java.

 client.java
 package io;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class client extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel contentPane2;
	private JTextField textField2;
	private JTextField textField_3;
	private JTextField textField_4;
	private Socket socket;
	private PrintWriter pw;
	private BufferedReader br;
	public client(String h) {
		setTitle(h);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 595, 365);
		contentPane2 = new JPanel();
		contentPane2.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane2);
		contentPane2.setLayout(null);
		JLabel label = new JLabel("客户端设置:");
		label.setBounds(10, 10, 79, 15);
		contentPane2.add(label);		
		JLabel lblServeIp = new JLabel("serve ip:");
		lblServeIp.setBounds(10, 35, 79, 15);
		contentPane2.add(lblServeIp);		
		textField2= new JTextField();
		textField2.setBounds(100, 32, 125, 21);
		contentPane2.add(textField2);
		textField2.setColumns(10);		
		JLabel lblServePort = new JLabel("serve port:");
		lblServePort.setBounds(250, 35, 79, 15);
		contentPane2.add(lblServePort);		
		textField_3 = new JTextField();
		textField_3.setBounds(339, 32, 119, 21);
		contentPane2.add(textField_3);
		textField_3.setColumns(10);		
		JTextArea textArea = new JTextArea();
		textArea.setBounds(20, 66, 530, 206);
		contentPane2.add(textArea);
		try {
			InetAddress address=InetAddress.getLocalHost();
			textField2.setText(address.getHostAddress());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JButton btnConnect = new JButton("connect");
		btnConnect.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new Thread() {
		            public void run() {
				int port=Integer.parseInt(textField_3.getText());
				try {
				socket=new Socket(textField2.getText(),port);
				textArea.append("Connect to server…\n");
				}catch (Exception e1) {
					e1.printStackTrace();
					//textArea.append("Connect to server…");
			}
		            }
		        }.start();
		        new Thread() {
		            public void run() {		                
		                    while (true) {
		                    	try {
				                	br = new BufferedReader(new InputStreamReader(
			                                socket.getInputStream()));
		                        String message = br.readLine();
		                        textArea.setText(textArea.getText() + message
		                                + "\r\n");
		                    }
		                 catch (Exception e) {		                    
		                }
		                    }
		            }
		        }.start();
		    }
		});
		btnConnect.setBounds(474, 31, 97, 23);
		contentPane2.add(btnConnect);
		JLabel lblSay = new JLabel("say:");
		lblSay.setBounds(10, 282, 88, 36);
		contentPane2.add(lblSay);
		textField_4 = new JTextField();
		textField_4.setBounds(73, 290, 351, 21);
		contentPane2.add(textField_4);
		textField_4.setColumns(10);	
		JButton btnSay = new JButton("say");
		btnSay.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String message= textField_4.getText();
				try {
					pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				pw.println(message);
				pw.flush();
			}
		});
		btnSay.setBounds(452, 289, 119, 23);
		contentPane2.add(btnSay);
	}
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					
					client frame2 = new client("客户端");
					frame2.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
		});
	}
}



serve.java.

package io;
import java.net.*;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.*;
public class serve extends JFrame {
	private static final long serialVersionUID = 1L;
	private JPanel contentPane1;
	private JTextField textField;
	private JTextField textField_1;
	private Socket socket;
	private PrintWriter pw1;
	private ServerSocket server;
	public static JTextArea textArea;
	static int result=0;
	client f1;
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					serve frame1 = new serve("服务器");
					frame1.setVisible(true);
				    } catch (Exception e) {
					e.printStackTrace();
				}
			}
			
		});
	}
	public serve(String s) {
		setTitle(s);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 599, 402);
		contentPane1 = new JPanel();
		contentPane1.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane1);
		contentPane1.setLayout(null);
		JLabel label = new JLabel("服务器设置:");
		label.setBounds(31, 5, 76, 15);
		contentPane1.add(label);
		JLabel lblPort = new JLabel("port:");
		lblPort.setBounds(31, 30, 58, 15);
		contentPane1.add(lblPort);
		textField = new JTextField();
		textField.setBounds(87, 25, 363, 21);
		contentPane1.add(textField);
		textField.setColumns(10);
		textArea = new JTextArea();
		textArea.setBounds(31, 69, 528, 239);
		contentPane1.add(textArea);
		JButton btnStart = new JButton("start");
		btnStart.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				 new Thread() {

		                public void run() {
		                	String i=textField.getText();
		    				int port=Integer.parseInt(i);
		    				try {
		    				server=new ServerSocket(port);
		    				textArea.append("Server starting…");
		    				while(true) {
		    				socket=server.accept();
		    				System.out.println("success");
		    				result=1;
		    				textArea.append("Client connected…\n");
		    				Thread st=new Thread(new ServerStream(socket));
		    				st.start();
		    				}
		                }catch (IOException e) {
							e.printStackTrace();
		                }	
						}
		            }.start();
		            new Thread() {
		            	public void run() {
		                    while(true){
		                        try {
		                            Thread.sleep(500);
		                        } catch (InterruptedException e) {
		                            // TODO Auto-generated catch block
		                            e.printStackTrace();
		                        }
		                        StringBuffer messagesb=new StringBuffer();
		                        for(String message:ServerStream.messages){ 		                        	
		                            messagesb.append(message+"\r");
		                        }
		                        if(result==1) {
		                        textArea.setText("Server starting…\n"+"Client connected…\n"+messagesb.toString());
		                        }
		                        else {
		                        	textArea.setText("Server starting…\n"+messagesb.toString());
		                        }
		                    }
		                }
		            }.start();
	             }
		});
		btnStart.setBounds(488, 24, 71, 23);
		contentPane1.add(btnStart);
		JLabel lblSay = new JLabel("say:");
		lblSay.setBounds(49, 336, 58, 15);
		contentPane1.add(lblSay);
		textField_1 = new JTextField();
		textField_1.setBounds(117, 334, 330, 18);
		contentPane1.add(textField_1);
		textField_1.setColumns(10);		
		JButton btnSay = new JButton("say");
		btnSay.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String message1= textField_1.getText();
				try {
					pw1 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				pw1.println(message1);
				pw1.flush();
			}
		});
		btnSay.setBounds(488, 332, 71, 23);
		contentPane1.add(btnSay);
	}
}


`ServeStream.java.

package io;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
public class ServerStream implements Runnable
{ 
      private Socket socket = null;
      public static List<String> messages = new ArrayList<String>();
      BufferedReader in;
      PrintWriter out;
      public ServerStream(Socket socket)
      {
      	 super();
      	 this.socket = socket;
      	try {
			in = new BufferedReader(new InputStreamReader( 
			 	    socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream(), true);
		} catch (IOException e) {
			e.printStackTrace();
		}
      }  
      public void run()
      {	  
      	try
      	{	
      	  while (true) {
              String message = in.readLine();
              if (message == null) {
                  break;
              }
               messages.add(message + "   \n");
      	    }
      	}
      	catch(IOException e)
      	{
      		e.printStackTrace();
      	}
      }
}

你可能感兴趣的:(Java基础聊天室基于Swing socket通信)