java 基于socket的局域网实时聊天116116

1.运行时电脑必须有网络
2.先开启服务器,然后再连接,可以同时启动多个端口监听,意味着你可以接收多个人的信息;
3.连接之后就不能关闭端口了,功能有待改善,

代码如下:

package text;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

public class Login extends JFrame{

private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField serverip;
private JTextField localip;
private JTextField localport;
private JTextField serverport;
private JButton BTNserverclose;
private JScrollPane scrollPane;
private JScrollPane scrollPane_1;
jiantin jian=new jiantin();
String ipaddress2;
JTextArea chattxt;
JTextArea fainfo;
JButton BTNfa;
JButton BTNserver;
JButton BTNlianjie;
Socket localsocket;
ServerSocket s;
DataOutputStream out;
String ipaddress;//对方内网ip
Socket cli;
String sport;//对方端口
JTextArea info;
int port;
int port2;



public static void main(String[] args) {
				Login frame = new Login();
				frame.setVisible(true);	
	}


public Login() {
	setTitle("\u767B   \u5F55");
	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	setBounds(100, 100, 460, 449);
	contentPane = new JPanel();
	contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
	setContentPane(contentPane);
	contentPane.setLayout(null);
	
	JLabel lblip = new JLabel("\u672C\u673A\u5185\u7F51ip\uFF1A");
	lblip.setFont(new Font("Adobe 黑体 Std R", Font.PLAIN, 14));
	lblip.setBounds(31, 10, 108, 29);
	contentPane.add(lblip);
	
	JLabel lblip_1 = new JLabel("\u8F93\u5165\u670D\u52A1\u5668 ip\uFF1A");
	lblip_1.setFont(new Font("Adobe 黑体 Std R", Font.PLAIN, 14));
	lblip_1.setBounds(31, 89, 108, 29);
	contentPane.add(lblip_1);
	
	localip = new JTextField();
	localip.setColumns(10);
	localip.setBounds(132, 15, 131, 21);
	contentPane.add(localip);
	try {
		localsocket=new Socket("www.baidu.com",80);
	} catch (UnknownHostException e) {
		JOptionPane.showMessageDialog(BTNserver, "网络连接错误,请检查网络!", "帮助", JOptionPane.INFORMATION_MESSAGE);
	} catch (IOException e) {
		e.printStackTrace();
	}
	localip.setText(localsocket.getLocalAddress().toString());
	localip.setEditable(false);
	
	serverip = new JTextField();
	serverip.setBounds(132, 94, 131, 21);
	contentPane.add(serverip);
	serverip.setColumns(10);
	serverip.setText("localhost");
	
	JLabel port1jpanel = new JLabel("\u7AEF\u53E3\uFF1A");
	port1jpanel.setFont(new Font("Adobe 黑体 Std R", Font.PLAIN, 14));
	port1jpanel.setBounds(31, 49, 43, 29);
	contentPane.add(port1jpanel);
	
	localport = new JTextField();
	localport.setColumns(10);
	localport.setBounds(132, 55, 50, 21);
	contentPane.add(localport);
	localport.setText("1234");
	
    BTNserver = new JButton("\u542F\u52A8\u670D\u52A1\u5668");
	BTNserver.setBounds(192, 54, 108, 23);
	contentPane.add(BTNserver);
	BTNserver.addActionListener(jian);
	
	BTNlianjie = new JButton("\u8FDE\u63A5\u670D\u52A1\u5668");
	BTNlianjie.addActionListener(jian);
	BTNlianjie.setBounds(323, 131, 113, 23);
	contentPane.add(BTNlianjie);
	
	JLabel port2 = new JLabel("\u7AEF\u53E3\uFF1A");
	port2.setFont(new Font("Adobe 黑体 Std R", Font.PLAIN, 14));
	port2.setBounds(273, 89, 43, 29);
	contentPane.add(port2);
	
	serverport = new JTextField();
	serverport.setColumns(10);
	serverport.setBounds(326, 94, 50, 21);
	contentPane.add(serverport);
	serverport.setText("1234");
	
	BTNserverclose = new JButton("\u5173\u95ED\u670D\u52A1\u5668");
	BTNserverclose.addActionListener(jian);
	BTNserverclose.setBounds(325, 54, 111, 23);
	contentPane.add(BTNserverclose);
	
	info = new JTextArea();
	info.setBounds(41, 128, 243, 106);
	contentPane.add(info);
	
    chattxt = new JTextArea();
	chattxt.setLineWrap(true);
	chattxt.setEditable(false);
	chattxt.setBounds(31, 244, 405, 124);
	contentPane.add(chattxt);
	
	fainfo = new JTextArea();
	fainfo.setBounds(47, 375, 253, 21);
	contentPane.add(fainfo);
	
	BTNfa = new JButton("\u53D1 \u9001");
	BTNfa.setBounds(313, 376, 108, 21);
	contentPane.add(BTNfa);
	
	
	scrollPane = new JScrollPane(chattxt);
	scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
	scrollPane.setBounds(41, 244, 395, 124);
	contentPane.add(scrollPane);
	scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
	
	scrollPane_1 = new JScrollPane(info);
	scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
	scrollPane_1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
	scrollPane_1.setBounds(41, 130, 259, 103);
	contentPane.add(scrollPane_1);
	
	JButton btnNewButton = new JButton("\u6E05  \u5C4F");
	btnNewButton.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent arg0) {
			chattxt.setText("");
			
		}
	});
	btnNewButton.setBounds(324, 211, 97, 23);
	contentPane.add(btnNewButton);

	BTNfa.addActionListener(jian);		
}//构造函数结尾

class jiantin implements ActionListener{

	
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==BTNserver) {
			if(localport.getText().equals("")) {
				JOptionPane.showMessageDialog(BTNserver, "端口为空", "帮助", JOptionPane.INFORMATION_MESSAGE);
                                                }
			else {
		        port=Integer.parseInt(localport.getText());
			    new Thread(new Runnable() {
				   public void run() {
					 try {
					    s=new ServerSocket(port);
					    
						Socket server = s.accept();  
						info.append(server.getInetAddress()+"    已经连接");
						DataInputStream in = new DataInputStream(server.getInputStream());
						
			                while(true) {
			                chattxt.append(server.getInetAddress()+"说: "+in.readUTF());
			            
			            	             }
			            	
			            	
			                        
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			                               }).start();
		   
		   info.append("端口:"+port+"  等待连接...."+"\n");
		   BTNserver.setText("已经启动");
		   BTNserver.setBackground(Color.red);
			  }
			
		}else if(e.getSource()==BTNlianjie) {
			ipaddress2=serverip.getText();
			port2=Integer.parseInt(serverport.getText());
			if(ipaddress2.equals("")||serverport.getText().equals("")) {
				JOptionPane.showMessageDialog(BTNserver, "端口或者IP有误!", "帮助", JOptionPane.INFORMATION_MESSAGE);
			}else {
				new Thread(new Runnable() {
					public void run() {
						try {
							cli=new Socket(ipaddress2,port2);
						} catch (UnknownHostException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						info.append("正在连接:"+ipaddress2+"  端口:"+port2+"\n");
						if(cli.isConnected()) 
						     info.append("连接成功  ^-^\n");
					}
				}).start();
			}
		}
		else if(e.getSource()==BTNserverclose) {
			
			try {
				info.append("端口:"+port+"  本地服务器关闭"+"\n");
				BTNserver.setText("启动服务器");
				BTNserver.setBackground(Color.lightGray);
				s.close();	
			}catch (Exception e1) {
				e1.printStackTrace();
			                      }
			                                   }
		else if(e.getSource()==BTNfa) {
				
				try {
					String tomess=fainfo.getText()+"\n";
					out = new DataOutputStream(cli.getOutputStream());
					out.writeUTF(tomess);
					chattxt.append("本机:"+tomess);
					fainfo.setText("");
					
				
				
				}catch (IOException e1) {
					e1.printStackTrace();
				}
				
			}	
  }

}
}

java 基于socket的局域网实时聊天116116_第1张图片

你可能感兴趣的:(java 基于socket的局域网实时聊天116116)