Java swing实现简单的C/S聊天及文件传输系统

本文分享了一篇使用Java Swing构建的简单C/S架构的聊天室程序,该程序支持点对点通信,能交换聊天内容并显示在列表框中,同时还具备文件传输功能。用户通过主界面的监听和连接按钮建立连接,实现消息发送和文件传输。
摘要由CSDN通过智能技术生成

很久没写博客了,这个本为课程设计,忙完了便抽空出来与大家分享一下,以便指正错误。


1、设计一个简单的聊天室程序。采用客户/服务器模式,分为客户端程序和服务器端程序。由于服务器只能支持一个客户,实际上是一个点对点通信的程序。客户端程序和服务器程序通过网络交换聊天字符串内容,并在窗口的列表框中显示。同时,实现了文件传输系统。

2、程序主界面(包含服务器端和客户端)。


3、先后点击监听和连接按钮即可建立互联。可以发送消息或传输文件。


4、其他不多说,直接上代码部分:

服务器:

public class chatServer extends JFrame implements Runnable,ActionListener{
	/**
	 * 
	 */
	private static final long serialVersionUID = -4929211394401993088L;
	//private static final int SERVICE_PORT=13;
	int SERVICE_PORT;
	DataInputStream in;
	DataOutputStream out;
	ServerSocket server;
	Socket nextClient;
	JTextField textField,nameField,portField;
	JTextArea textArea,textArea2;
	JButton button,fButton;
	JFileChooser chooser;
	MyradioButton lisButton,disButton;
	ButtonGroup group;
	Font font = new Font("Adobe 黑体 Std",0,16);
	JLabel label;
	

	
	public chatServer() {
		this.setTitle("Server");
		init();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(null);      
        this.setBounds(0, 0, 800, 500);
        this.setResizable(false);
        //this.setLocationRelativeTo(null);
        //this.setUndecorated(true);
        this.setLocation(1000,200);
        this.setVisible(true);	
	}
	
	@Override
	public void run(){
		
		try{

		while(true){

	        System.out.println("Server Start!");
			if(!lisButton.isSelected()) continue;					
			textArea.append("开始监听端口"+portField.getText()+"!\n");
			SERVICE_PORT=Integer.valueOf(portField.getText()).intValue();
			System.out.println("1");
			server=new ServerSocket(SERVICE_PORT);
			System.out.println("2");
				nextClient = server.accept();
				textArea.append("收到并接受客户端的连接请求!\n");
				in=new DataInputStream(nextClient.getInputStream());
				out=new DataOutputStream(nextClient.getOutputStream());
			while (true){
				String strUTF=in.readUTF();
				if(strUTF.equals("&&close&&")) {disButton.setSelected(true);out.writeUTF("&&close&&");break;}
	        	if(strUTF.equals("&&file.start&&"))
	        	{    		
	        		String fileName =in.readUTF();		        		
	        		chooser.setSelectedFile(new File(fileName)); 	        		
	        		int returnVal=chooser.showSaveDialog(this.getCon
  • 10
    点赞
  • 57
    收藏
    觉得还不错? 一键收藏
  • 27
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值