JAVA基于C/S模式的聊天小程序

简要介绍:
代码功能比较简单,可实现互发文字消息,单向由客户端向服务器传输文件及图片

Server.java

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.*;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;

class ServerThread extends Thread
{
	final int port=2345;
	ServerSocket server;
	Socket client;
	InputStreamReader in;
	BufferedReader reader;
	PrintWriter writer;
	Server s;
	public  ServerThread(Server s)
	{
		this.s=s;
		s.setServerThread(this);
		try
		{
		    //client=new Socket(str,port);
			server=new ServerSocket(port);
			client=server.accept();
			System.out.println("服务器套接字建立");
			in=new InputStreamReader(client.getInputStream());
			reader=new BufferedReader(in);//读取客户端发来的信息
			writer=new PrintWriter(client.getOutputStream(),true);//向客户端写信息
				
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		start();
	}
	public void run()
	{
		
		while(true)
		{
			try
			{
				String meaasge="";
				meaasge=reader.readLine();
				if (meaasge!=null&&meaasge.trim()!="")
				{
					s.receiveArea.append(meaasge+"\n");
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		
		
		}
	
		
	}
	
	public void SendMessage(String message)//发送文字消息
	{
		try
		{
			writer.println("服务器:"+message);
			
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}	
	
	public static void receiveFile(Socket client) throws IOException //服务器只负责接收文件
    {
        byte[] inputByte = null;
        int length = 0;
        DataInputStream din = null;
        FileOutputStream fout = null;
        try {
            din = new DataInputStream(client.getInputStream());
            
            fout = new FileOutputStream(new File("D:\\"+din.readUTF()));
            inputByte = new byte[1024];
            System.out.println("开始接收数据...");
            while (true)
            {
                if (din != null)
                {
                    length = din.read(inputByte, 0, inputByte.length);
                }
                if (length == -1)
                {
                    break;
                }
                System.out.println(length);
                fout.write(inputByte, 0, length);
                fout.flush();
            }
            System.out.println("完成接收");
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally
        {
            if (fout != null)
                fout.close();
            if (din != null)
                din.close();
            if (client != null)
                client.close();
        }
    }
	


}
	

public class Server extends JFrame
{
	ServerThread st;
	JLabel ipLabel =new JLabel("IP地址:");
	JTextField ipField =new JTextField(10);
	JLabel portLabel=new JLabel("端口:");
	JTextField portField=new JTextField(5);
	JButton button1=new JButton("连接");
	JButton button=new JButton("接收文件");
	JPanel panel1=new JPanel();
	

	
	JTextField sendField=new JTextField(20);
	JButton button2=new JButton("发送");
	JPanel panel2=new JPanel();
	
	JTextArea sendArea=new JTextArea(10,30);
	JTextArea receiveArea=new  JTextArea(10,30);
	JTextArea fileArea=new JTextArea(4,12);
	JPanel panel3=new JPanel();
	
	JLabel label1=new JLabel();
	JLabel label2=new JLabel();
	JPanel panel4=new JPanel();
	 public static String getLocalIP()//获取本机IP地址
	 {
	    	InetAddress addr = null;
	         try 
	         {
	            addr = InetAddress.getLocalHost();
	         } 
	         catch (UnknownHostException e) 
	         {
	             e.printStackTrace();
	              return null;
	         }
	         byte[] ipAddr = addr.getAddress();
	         String ipAddrStr = "";
	         for (int i = 0; i < ipAddr.length; i++) 
	         {	 
	             if (i > 0) 
	             {
	                 ipAddrStr += ".";
	             }
	             ipAddrStr += ipAddr[i] & 0xFF;
	         }
	         //System.out.println(ipAddrStr);
	                 return ipAddrStr;
	                 
	     }
	
	 public void setServerThread(ServerThread st) 
		{
			this.st = st;
		}
	public Server()
	{
		super("服务器");
		setSize(800,400);
		setLocation(500, 0);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
		
		panel1.setLayout(new FlowLayout());
		panel1.add(ipLabel);
		panel1.add(ipField);
		panel1.add(portLabel);
		panel1.add(portField);
		panel1.add(button1);
		panel1.add(button);
		
		panel2.setLayout(new BorderLayout());
		JLabel label=new JLabel("文件信息区");
		JPanel panel=new JPanel();
		panel.setLayout(new FlowLayout());
		panel.add(sendField);
		panel.add(button2);
		panel2.add(label,BorderLayout.NORTH);
		panel2.add(fileArea,BorderLayout.CENTER);
		panel2.add(panel,BorderLayout.SOUTH);
		
		
		panel3.setLayout(new FlowLayout());
		label1.setText("发

区"); panel3.add(label1); panel3.add(sendArea); panel4.setLayout(new FlowLayout()); label2.setText("接

区"); panel4.add(label2); panel4.add(receiveArea); Container container=getContentPane(); container.setLayout(new BorderLayout()); container.add(panel1,BorderLayout.NORTH); container.add(panel2,BorderLayout.SOUTH); container.add(panel3,BorderLayout.WEST); container.add(panel4,BorderLayout.CENTER); sendArea.append("请点击连接键,获取IP地址及端口号"); button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { sendArea.setText(""); String ipstr=getLocalIP(); System.out.println("服务器建立连接成功"); System.out.println("IP地址为:"+ipstr); ipField.setText(ipstr); portField.setText(st.port+""); } catch (Exception e2) { e2.printStackTrace(); } } }); button2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String message=""; message=sendField.getText(); if (message!=null&&message.trim()!="") { sendArea.append("服务器:"+message+"\n"); st.SendMessage(message); sendField.setText(""); } } }); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { fileArea.append("开始接收\n"); st.client=st.server.accept(); fileArea.append("有连接。。。\n"); st.receiveFile(st.client); fileArea.append("文件接收完毕,默认存储于D盘根目录下"); } catch (IOException e2) { e2.printStackTrace(); } } }); } public static void main(String[] args) { Server s=new Server(); ServerThread st=new ServerThread(s); } }

Client.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;


class ClientThread extends Thread
{
	final int port=2345;
	ServerSocket server;
	Socket client;
	InputStreamReader in;
	BufferedReader reader;
	PrintWriter writer;
	Client c;
	public  ClientThread(String ip,Client c)
	{
		this.c=c;
		try
		{
		    client=new Socket(ip,port);
		    SocketAddress endpoint=new InetSocketAddress(ip,port);
		    client.connect(endpoint, 5*1000);
			System.out.println("客户端套接字建立");
			in=new InputStreamReader(client.getInputStream());
			reader=new BufferedReader(in);//读取客户端发来的信息
			writer=new PrintWriter(client.getOutputStream(),true);//向客户端写信息
				
		} 
		catch (IOException e) {
			e.printStackTrace();
		}
	
		start();
	}
	public void run()
	{
		String meaasge="";
		while(true)
		{
			try
			{
				meaasge=reader.readLine();
			} 
			catch (NullPointerException e) {
				System.out.println("连接错误");
				System.exit(-1);
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			if (meaasge!=null&&meaasge.trim()!="")
			{
				c.receiveArea.append(meaasge+"\n");
			}
		}
	
		
	}
	
	public void SendMessage(String message)//发送文字消息
	{
		try
		{
			writer.println("客户端:"+message);
			
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}		
	
	public  void SendFile()//发送文件
	{
		JFileChooser jfc=new JFileChooser();
		jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
		jfc.showDialog(new JLabel(), "选择");
		File file=jfc.getSelectedFile();
		String filename=file.getName();
		c.fileArea.append(filename);
		int length = 0;
        byte[] sendByte = null;
        
        DataOutputStream dout = null;
        FileInputStream fin = null;
        String ip=null;
    
        ip=c.ipField.getText();
        try 
        {
            try
            {
            	if (ip!=""&&c.portField.getText()!="")
				{
                    client = new Socket();
                    client.connect(new InetSocketAddress(ip,port),10 * 1000);
                    dout = new DataOutputStream(client.getOutputStream());
                     file = new File(file.getAbsolutePath() );//读取选择指定路径下的文件
                    fin = new FileInputStream(file);
                    sendByte = new byte[1024];
                    dout.writeUTF(file.getName());
                    while((length = fin.read(sendByte, 0, sendByte.length))>0)
                    {
                        dout.write(sendByte,0,length);
                        dout.flush();
                    }
				}
      
         } 
            catch (Exception e1)
              {

              }
            finally
            {
                  if (dout != null)
                      dout.close();
                  if (fin != null)
                      fin.close();
                  if (client!= null)
                      client.close();
          }
          } catch (Exception e1) 
          {
              e1.printStackTrace();
          }
		
	
	}


}
public class Client extends JFrame
{
	ClientThread ct;
	
	JLabel ipLabel =new JLabel("IP地址:");
	JTextField ipField =new JTextField(10);
	JLabel portLabel=new JLabel("端口:");
	JTextField portField=new JTextField(5);
	JButton button1=new JButton("连接");
	JButton button=new JButton("发送文件");
	JPanel panel1=new JPanel();
	
	JTextField sendField=new JTextField(20);
	JButton button2=new JButton("发送");
	JPanel panel2=new JPanel();
	
	JTextArea sendArea=new JTextArea(10,30);
	JTextArea receiveArea=new  JTextArea(10,30);
	JTextArea fileArea=new JTextArea(4,12);
	JPanel panel3=new JPanel();
	
	JLabel label1=new JLabel();
	JLabel label2=new JLabel();
	JPanel panel4=new JPanel();
	public void setClient(ClientThread ct)
	{
		this.ct = ct;
	}
 
	  public Client()
   {
		super("客户端");
		setSize(800,400);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
		
	
		panel1.setLayout(new FlowLayout());
		panel1.add(ipLabel);
		panel1.add(ipField);
		panel1.add(portLabel);
		panel1.add(portField);
		panel1.add(button1);
		panel1.add(button);
		
		
		panel2.setLayout(new BorderLayout());
		JLabel label=new JLabel("文件信息区");
		JPanel panel=new JPanel();
		panel.setLayout(new FlowLayout());
		panel.add(sendField);
		panel.add(button2);
		panel2.add(label,BorderLayout.NORTH);
		panel2.add(fileArea,BorderLayout.CENTER);
		panel2.add(panel,BorderLayout.SOUTH);
		
		panel3.setLayout(new FlowLayout());
		label1.setText("发

区"); panel3.add(label1); panel3.add(sendArea); panel4.setLayout(new FlowLayout()); label2.setText("接

区"); panel4.add(label2); panel4.add(receiveArea); Container container=getContentPane(); container.setLayout(new BorderLayout()); container.add(panel1,BorderLayout.NORTH); container.add(panel2,BorderLayout.SOUTH); container.add(panel3,BorderLayout.WEST); container.add(panel4,BorderLayout.CENTER); // container.add(fileArea,BorderLayout.EAST); sendArea.append("请输入IP地址后,点击连接键"); button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sendArea.setText(""); try { String ipstr=""; if (ipField.getText()!="") { ipstr=ipField.getText(); } ct=new ClientThread(ipstr,Client.this); Client.this.setClient(ct); System.out.println("客户端建立连接成功"); portField.setText(ct.port+""); } catch (Exception e2) { System.out.println("连接失败"); } } }); button2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String message=""; message=sendField.getText(); if (message!=null&&message.trim()!="") { sendArea.append("客户端:"+message+"\n"); ct.SendMessage(message); sendField.setText(""); } } }); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ct.SendFile(); if (fileArea.getText()!="") { String file=fileArea.getText(); ct.SendMessage(file); } } }); } public static void main(String[] args) { new Client(); } }

运行图片
点击连接键,获取服务器端IP地址,端口号已默认选择2345,

JAVA基于C/S模式的聊天小程序_第1张图片

输入IP地址,点击连接键,端口号已默认,不用再输入

JAVA基于C/S模式的聊天小程序_第2张图片

你可能感兴趣的:(JAVA基于C/S模式的聊天小程序)