极客教学笔记---Java实现简单聊天客户端模拟


偶然间在网上看见的教程,想着弥补下自己对java的空白就写了这个学习一下。结果来说不够完善,关于UTF-8接受方会出现乱码。在此仅用于以后参考工程结构。

MySocketServer:

package testmySocket.main;

public class MySocketServer {
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new ServerListener().start();
	}

}

ServerListener:

package testmySocket.main;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JOptionPane;

public class ServerListener extends Thread {
	public void run(){
		//1-65535
		try{
			ServerSocket serverSocket = new ServerSocket(12345);
			while(true){
				//block
				Socket socket = serverSocket.accept();
				//building link
				JOptionPane.showMessageDialog(null, "有客户端连接到了本机的12345号端口");
				//将Socket传递给新的线程
				ChatSocket cs = new ChatSocket(socket);
				cs.start();
				ChatManager.getChatManager().add(cs);
			}
		} catch(IOException e){
			e.printStackTrace();
		}
	}
}

ChatSocket:

package testmySocket.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

public class ChatSocket extends Thread {
	Socket socket;
	public ChatSocket(Socket s){
		this.socket = s;
	}
	
	public void out(String out){
		try {
			socket.getOutputStream().write(out.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void run(){
		try {
			BufferedReader br = new 
					BufferedReader(new 
							InputStreamReader(socket.getInputStream(),"UTF-8"));
			String line = null;
			while((line = br.readLine())!=null){
				System.out.println(line);
				ChatManager.getChatManager().publish(this, line);
			}
			br.close();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
  

ChatManager:

package testmySocket.main;

import java.util.Vector;

public class ChatManager {
	private  ChatManager(){}
	private static final ChatManager cm = new ChatManager();
	public static ChatManager getChatManager(){
		return cm;
	}
	Vector<ChatSocket> vector = new Vector<ChatSocket>();
	
	public void add(ChatSocket cs){
		vector.add(cs);
	}
	
	public void publish(ChatSocket cs,String out){
		for(int i=0 ; i<vector.size() ; i++){
			ChatSocket csChatSocket = vector.get(i);
			if(!cs.equals(csChatSocket)){
				csChatSocket.out(out+"\n");
			}
		}
	}
}

StartClient:

package test2;

import java.awt.EventQueue;

import test3.MainWindow;

public class StartClient {

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainWindow frame = new MainWindow();
					frame.setVisible(true);
					ChatManager.getCM().setWindow(frame);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

}

MainWindow:

package test3;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import test2.ChatManager;

import javax.swing.JTextArea;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MainWindow extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	JTextArea txt;

	 /** 
	 * Create the frame.
	 */
	public MainWindow() {
		setAlwaysOnTop(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		txt = new JTextArea();
		txt.setText("Ready...");
		
		JTextArea Ip = new JTextArea();
		Ip.setText("127.0.0.1");
		
		JButton button = new JButton("\u8FDE\u63A5\u5230\u670D\u52A1\u5668");
		button.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				ChatManager.getCM().connect(Ip.getText());
			}
		});
		
		JTextArea send = new JTextArea();
		send.setText("\u4F60\u597D");
		
		JButton button_1 = new JButton("\u53D1\u9001");
		button_1.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				ChatManager.getCM().send(send.getText());
				appendText("我说:"+send.getText());
				send.setText(" ");
			}
		});
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
					.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
						.addComponent(txt, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 423, Short.MAX_VALUE)
						.addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup()
							.addComponent(Ip)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(button))
						.addGroup(gl_contentPane.createSequentialGroup()
							.addComponent(send, GroupLayout.DEFAULT_SIZE, 345, Short.MAX_VALUE)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(button_1)))
					.addContainerGap())
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
						.addComponent(button)
						.addComponent(Ip, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(txt, GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
						.addComponent(button_1)
						.addComponent(send, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
		);
		contentPane.setLayout(gl_contentPane);
	}
	
	public void appendText(String in){
		txt.append("\n"+in);
	}
}

ChatManager:

package test2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import test3.MainWindow;

public class ChatManager {
	
	private ChatManager(){};
	private static final ChatManager instance = new ChatManager();
	public static ChatManager getCM(){
		return instance;
	}
	
	MainWindow window;
	private String Ip;
	Socket socket;
	BufferedReader reader;
	PrintWriter writer;
	
	public void setWindow(MainWindow window){
		this.window = window;
		window.appendText("文本框已经和ChatManager绑定。");
	}
	
	public void connect(String ip){
		this.Ip = ip;
		new Thread(){

			@Override
			public void run() {
				try {
					socket = new Socket(Ip,12345);
					writer = new PrintWriter(
							 new OutputStreamWriter(socket.getOutputStream()));
					reader = new BufferedReader(
							 new InputStreamReader(socket.getInputStream(),"UTF-8"));
					String line = null;
					while((line = reader.readLine()) != null){
						window.appendText("收到:"+line);
					}
					writer.close();
					reader.close();
					writer = null;
					reader = null;
					
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e){
					e.printStackTrace();
				}
			}
			 
			
		}.start();
	}
	
	public void send(String out){
		if(writer != null){
			writer.write(out+"\n");
			writer.flush();
		}else{
			window.appendText("当前链接已经中断...");
		}
	}
}

最终效果图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值