java实现客户端与服务端互传信息聊天(带界面)

因为想要在每条信息前面标注时间,所以写了下面这个类来返回系统当前时间:

public class GetDate {
	
	public static String getCurDate() {
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String curdate = simpleDateFormat.format(date);
		return curdate;
	}
}

服务端与客户端为了可以调节接受信息框里的字体,所以使用的JTEXTPANE。

输入框使用的JTEXTAREA。

接下来是服务端代码:

public class Server extends JFrame {
	private static ServerSocket ss;
	private static Socket s;
	private static DataInputStream dis;
	private static DataOutputStream dos;
	private static String string_send;
	private static String string_rec;
	
	private static JTextPane jtp_down;
	private static JTextPane jtp_up;
	private static JScrollPane jsp_up;
	private static JScrollPane jsp_down;
	private static JPanel jpl_bottom;
	private static JPanel jpl_btn;
	private static JButton jbt_send;
	private static JMenuBar jmb_bar;
	private static JMenu jme_file;
	private static JMenuItem jmi_send;
	
	private void ServerConnect() throws IOException{
		ss = new ServerSocket(8080);
		s = ss.accept();	
		dis = new DataInputStream(s.getInputStream());
		dos = new DataOutputStream(s.getOutputStream());
		 while(true) {    
			 string_rec = dis.readUTF();   
             SimpleAttributeSet attrset = new SimpleAttributeSet();
             Document docs = jtp_up.getDocument();     
             try {
         		 jtp_up.setCaretPosition(jtp_up.getDocument().getLength());
                 StyleConstants.setFontSize(attrset,16);
            	 docs.insertString(docs.getLength(), GetDate.getCurDate()+"\r\n", attrset);
                 StyleConstants.setFontSize(attrset,24);
                 docs.insertString(docs.getLength(), "client:"+string_rec+"\r\n", attrset);
             } catch (BadLocationException e) {
                 e.printStackTrace();
             }
         }  
	}
	
	private void JmenuBarSet(){
		jmb_bar = new JMenuBar();
		jme_file = new JMenu("文件");
		jmi_send = new JMenuItem("发送文件");
		jmb_bar.add(jme_file);
		jme_file.add(jmi_send);
	}
	
	private void JbuttonSet(){
		jbt_send = new JButton("Send");
	}
	
	private void JtextPaneSet(){
		jtp_up = new JTextPane();
		jtp_down = new JTextPane();
		jtp_up.setEditable(false);
	}
	
	private void JscrollPaneSet(){
		JtextPaneSet();
		jsp_up = new JScrollPane(jtp_up);
		jsp_down = new JScrollPane(jtp_down);
		jsp_up.setPreferredSize(new Dimension(500,300));
		jsp_down.setPreferredSize(new Dimension(500,130));
	}
	
	private void JpanelSet(){
		JscrollPaneSet();
		JbuttonSet();
		jpl_bottom = new JPanel();
		jpl_btn = new JPanel();
		jpl_bottom.setLayout(new BorderLayout());
		jpl_bottom.add(jsp_up,BorderLayout.NORTH);
		jpl_bottom.add(jsp_down,BorderLayout.CENTER);
		jpl_btn.add(jbt_send);		
	}
	
	public Server(){
		JmenuBarSet();
		JpanelSet();
		this.setLayout(new BorderLayout());
		this.add(jmb_bar,BorderLayout.NORTH);
		this.add(jpl_bottom,BorderLayout.CENTER);
		this.add(jpl_btn,BorderLayout.SOUTH);
		this.setTitle("Server");
		this.setSize(500, 500);
		this.setVisible(true);
		this.setResizable(false);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		jbt_send.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				string_send = jtp_down.getText();
				try {
					dos.writeUTF(string_send);
					jtp_down.setText("");
					SimpleAttributeSet attrset = new SimpleAttributeSet();	 
					jtp_up.setCaretPosition(jtp_up.getDocument().getLength());
		            Document docs = jtp_up.getDocument();     
		            try {
		            	StyleConstants.setFontSize(attrset,16);
		            	docs.insertString(docs.getLength(), GetDate.getCurDate()+"\r\n", attrset);
		            	StyleConstants.setFontSize(attrset,24);
		                docs.insertString(docs.getLength(), "me:"+string_send+"\r\n", attrset);
		            } catch (BadLocationException be) {
		                be.printStackTrace();
		            }
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		
	}
	
	public static void main(String args[]) throws Exception{
		Server server = new Server();
		server.ServerConnect();
	}	
}

下面是客户端代码:

public class Client extends JFrame {
	private static Socket s;
	private static DataOutputStream dos;
	private static DataInputStream dis;
	private static String string_send;
	private static String string_rec;

	private static JTextPane jtp_down;
	private static JTextPane jtp_up;
	private static JScrollPane jsp_up;
	private static JScrollPane jsp_down;
	private static JPanel jpl_bottom;
	private static JPanel jpl_btn;
	private static JButton jbt_send;
	private static JScrollBar jsb_bar; 
	private static JMenuBar jmb_bar;
	private static JMenu jme_file;
	private static JMenuItem jmi_send;
	
	public void ClientConnect() throws UnknownHostException, IOException{
		s = new Socket("127.0.0.1",8080);
		dis = new DataInputStream(s.getInputStream());
		dos = new DataOutputStream(s.getOutputStream());
		while(true){			
			 string_rec = dis.readUTF();   
             SimpleAttributeSet attrset = new SimpleAttributeSet();
             Document docs = jtp_up.getDocument();  
             try {
         		 jtp_up.setCaretPosition(jtp_up.getDocument().getLength());
            	 StyleConstants.setFontSize(attrset,16);
            	 docs.insertString(docs.getLength(), GetDate.getCurDate()+"\r\n", attrset);
            	 StyleConstants.setFontSize(attrset,24);
                 docs.insertString(docs.getLength(), "server:"+string_rec+"\r\n", attrset);
             } catch (BadLocationException e) {
                 e.printStackTrace();
             }
		}
	}
	
	private void JmenuBarSet(){
		jmb_bar = new JMenuBar();
		jme_file = new JMenu("文件");
		jmi_send = new JMenuItem("发送文件");
		jmb_bar.add(jme_file);
		jme_file.add(jmi_send);
	}

	private void JbuttonSet(){
		jbt_send = new JButton("Send");
	}
	
	private void JtextPaneSet(){
		jtp_up = new JTextPane();
		jtp_down = new JTextPane();
		jtp_up.setEditable(false);
	}
	
	private void JscrollPaneSet(){
		JtextPaneSet();
		jsp_up = new JScrollPane(jtp_up);
		jsp_down = new JScrollPane(jtp_down);
		jsp_up.setPreferredSize(new Dimension(500,300));
		jsp_down.setPreferredSize(new Dimension(500,130));
		jsb_bar = jsp_up.getVerticalScrollBar(); 
		jsb_bar.setValue(jsb_bar.getMaximum()); 
	}
	
	private void JpanelSet(){
		JscrollPaneSet();
		JbuttonSet();
		jpl_bottom = new JPanel();
		jpl_btn = new JPanel();
		jpl_bottom.setLayout(new BorderLayout());
		jpl_bottom.add(jsp_up,BorderLayout.NORTH);
		jpl_bottom.add(jsp_down,BorderLayout.CENTER);
		jpl_btn.add(jbt_send);		
	}
	
	public Client(){
		JmenuBarSet();
		JpanelSet();
		this.setLayout(new BorderLayout());
		this.add(jmb_bar,BorderLayout.NORTH);
		this.add(jpl_bottom,BorderLayout.CENTER);
		this.add(jpl_btn,BorderLayout.SOUTH);
		this.setTitle("Client");
		this.setSize(500, 500);
		this.setVisible(true);
		this.setResizable(false);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		jbt_send.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				string_send = jtp_down.getText();
				try {
					dos.writeUTF(string_send);
					jtp_down.setText("");
					SimpleAttributeSet attrset = new SimpleAttributeSet();
					jtp_up.setCaretPosition(jtp_up.getDocument().getLength());
		            Document docs = jtp_up.getDocument();      
		            try {
		            	StyleConstants.setFontSize(attrset,16);
		            	docs.insertString(docs.getLength(), GetDate.getCurDate()+"\r\n", attrset);
		            	StyleConstants.setFontSize(attrset,24);
		                docs.insertString(docs.getLength(), "me:"+string_send+"\r\n", attrset);
		            } catch (BadLocationException be) {
		                be.printStackTrace();
		            }
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		
	}
	
	public static void main(String args[]) throws Exception{
		Client client = new Client();
		client.ClientConnect();
	}

}

图:



  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的基于 Java Socket 编写的客户端服务端聊天程序。客户端服务端都有一个 GUI 界面,可以通过界面输入和接收消息。 客户端界面: ![客户端界面](https://i.imgur.com/2VBKkLj.png) 服务端界面: ![服务端界面](https://i.imgur.com/ArQ8D6C.png) 客户端代码: ```java import java.awt.BorderLayout; 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.PrintWriter; import java.net.Socket; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class ChatClient { private BufferedReader in; private PrintWriter out; private JFrame frame = new JFrame("Chat Client"); private JTextField textField = new JTextField(40); private JTextArea messageArea = new JTextArea(8, 60); public ChatClient() { // Layout GUI textField.setEditable(false); messageArea.setEditable(false); frame.getContentPane().add(textField, BorderLayout.SOUTH); frame.getContentPane().add(new JScrollPane(messageArea), BorderLayout.CENTER); frame.pack(); // Add Listeners textField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { out.println(textField.getText()); textField.setText(""); } }); } private String getServerAddress() { return "localhost"; // Change this to your server's IP address } private int getServerPort() { return 9001; // Change this to your server's port number } public void run() throws IOException { // Make connection and initialize streams Socket socket = new Socket(getServerAddress(), getServerPort()); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); // Process all messages from server, according to the protocol. while (true) { String line = in.readLine(); if (line.startsWith("SUBMITNAME")) { out.println(getName()); } else if (line.startsWith("NAMEACCEPTED")) { textField.setEditable(true); } else if (line.startsWith("MESSAGE")) { messageArea.append(line.substring(8) + "\n"); } } } private String getName() { return "Client"; // Change this to your desired name } public static void main(String[] args) throws Exception { ChatClient client = new ChatClient(); client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); client.frame.setVisible(true); client.run(); } } ``` 服务端代码: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.HashSet; import java.util.Set; public class ChatServer { private static final int PORT = 9001; private static Set<String> names = new HashSet<String>(); private static Set<PrintWriter> writers = new HashSet<PrintWriter>(); public static void main(String[] args) throws Exception { System.out.println("The chat server is running."); ServerSocket listener = new ServerSocket(PORT); try { while (true) { new Handler(listener.accept()).start(); } } finally { listener.close(); } } private static class Handler extends Thread { private String name; private Socket socket; private BufferedReader in; private PrintWriter out; public Handler(Socket socket) { this.socket = socket; } public void run() { try { // Create character streams for the socket. in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); // Request a name from this client. Keep requesting until // a name is submitted that is not already used. Note that // checking for the existence of a name and adding the name // must be done while locking the set of names. while (true) { out.println("SUBMITNAME"); name = in.readLine(); if (name == null) { return; } synchronized (names) { if (!names.contains(name)) { names.add(name); break; } } } // Now that a successful name has been chosen, add the // socket's print writer to the set of all writers so // this client can receive broadcast messages. out.println("NAMEACCEPTED"); writers.add(out); // Accept messages from this client and broadcast them. // Ignore other clients that cannot be broadcasted to. while (true) { String input = in.readLine(); if (input == null) { return; } for (PrintWriter writer : writers) { writer.println("MESSAGE " + name + ": " + input); } } } catch (IOException e) { System.out.println(e); } finally { // This client is going down! Remove its name and its print // writer from the sets, and close its socket. if (name != null) { names.remove(name); } if (out != null) { writers.remove(out); } try { socket.close(); } catch (IOException e) { } } } } } ``` 希望这个程序能够帮到您!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值