java中UDP简单聊天程序

  学过计算机网络通信的都知道,计算机之间传送数据由两种,即TCP通信和UDP通信。TCP是可靠的面向连接的通信协议,二UDP是不可靠的面向无连接的通信协议。

  java中有基于TCP的网络套接字通信,也有基于UDP的用户数据报通信,UDP的信息传输速度快,但不可靠!

  基于UDP通信的基本模式:

 (1)将数据打包,称为数据包(好比将信件装入信封一样),然后将数据包发往目的地。

 (2)接受别人发来的数据包(好比接收信封一样),然后查看数据包中的内容。

客户机

package com.client.view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ObjectOutputStream;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import com.tools.ClientToServerThread;

/**
 * @author lenovo
 *
 */
public class JChatFrm extends JFrame implements ActionListener{

	
	JTextArea jta;
	JTextField jtf;
	JButton jb;
	JPanel jp;
	String ownerId;
	String friendId;
	
	ClientToServerThread ctsT;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new JChatFrm();
	}
	
	public JChatFrm()
	{
		setTitle("客户端");
		jta=new JTextArea();
		jtf=new JTextField(15);
		jb=new JButton("发送");
		jb.addActionListener(this);
		jp=new JPanel();
		jp.add(jtf);
		jp.add(jb);
		
		this.add(jta,"Center");
		this.add(jp,"South");
	//	this.setTitle(ownerId+" 正在和 "+friend+" 聊天");
		this.setIconImage((new ImageIcon("image/qq.gif").getImage()));
	//	this.setSize(300, 200);
		this.setBounds(300, 200, 300, 200);
		this.setVisible(true);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		ctsT = new ClientToServerThread(jta);
		ctsT.start();
		
		/**窗体关闭按钮事件*/
		this.addWindowListener(new WindowAdapter()
		{
			public void windowClosing(WindowEvent e)
			{
				if(JOptionPane.showConfirmDialog(null, "<html><font size=
  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值