时间:2021-05-19
学过计算机网络通信的都知道,计算机之间传送数据由两种,即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=3>确定退出吗?</html>","系统提示",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE)==0)
{
System.exit(0);
ctsT.closeSocket();
}
else
{
return;
}
}
}
);
}
//写一个方法,让它显示消息
public void showMessage(String message)
{
String info= message;
this.jta.append(info);
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getSource()==jb)
{
byte buffer[] = jtf.getText().trim().getBytes();
ctsT.sendData(buffer);
}
}
}
复制代码 代码如下:
package com.tools;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Properties;
import javax.swing.JTextArea;
import com.common.User;
/**
* @author lenovo
*
*/
public class ClientToServerThread extends Thread{
private String serverIP = "127.0.0.1";
private int serverPORT = 8888;
private int receivePORT = 6666;
//声明发送信息的数据报套结字
private DatagramSocket sendSocket = null;
//声明发送信息的数据包
private DatagramPacket sendPacket = null;
//声明接受信息的数据报套结字
private DatagramSocket receiveSocket = null;
//声明接受信息的数据报
private DatagramPacket receivePacket = null;
//收发数据的端口
private int myPort = 0;
//接收数据主机的IP地址
private String friendIP = null;
private int friendPort = 0;
//缓冲数组的大小
public static final int BUFFER_SIZE = 5120;
private byte inBuf[] = null; //接收数据的缓冲数组
private byte outBuf[] = null; //发送数据的缓冲数组
JTextArea jta;
// 构造函数
public ClientToServerThread(JTextArea jta) {
this.jta = jta;
getPropertiesInfo();
}
public void run() {
String receiveInfo = "";
try{
inBuf = new byte[BUFFER_SIZE];
receivePacket = new DatagramPacket(inBuf,inBuf.length);
receiveSocket = new DatagramSocket(receivePORT);
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
while (true) {
if(receiveSocket == null){
break;
} else {
try {
receiveSocket.receive(receivePacket);
String message = new String(receivePacket.getData(),0,receivePacket.getLength());
jta.append("收到数据"+message+"\n");
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
}
}
/**
* 该方法用来获得服务器属性文件中的IP、PORT
*/
private void getPropertiesInfo(){
Properties prop = new Properties();
InputStream inStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("ServerInfo.properties");
try{
//获得相应的键值对
prop.load(inStream);
}catch(IOException e){
e.printStackTrace();
}
//根据相应的键获得对应的值
serverIP = prop.getProperty("serverip");
serverPORT = Integer.parseInt(prop.getProperty("serverudp.port"));
receivePORT = Integer.parseInt(prop.getProperty("receiveudp.port"));
}
public void sendData(byte buffer[]){
try{
InetAddress address = InetAddress.getByName(serverIP);
//outBuf = new byte[BUFFER_SIZE];
sendPacket = new DatagramPacket(buffer,buffer.length,address,serverPORT);
sendSocket = new DatagramSocket();
sendSocket.send(sendPacket);
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
public void closeSocket(){
receiveSocket.close();
}
}
服务器:
复制代码 代码如下:
package com.server.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=3>确定退出吗?</html>","系统提示",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE)==0)
{
System.exit(0);
ctsT.closeSocket();
}
else
{
return;
}
}
}
);
}
//写一个方法,让它显示消息
public void showMessage(String message)
{
String info= message;
this.jta.append(info);
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getSource()==jb)
{
byte buffer[] = jtf.getText().trim().getBytes();
ctsT.sendData(buffer);
}
}
}
复制代码 代码如下:
package com.tools;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Properties;
import javax.swing.JTextArea;
import com.common.User;
/**
* @author lenovo
*
*/
public class ClientToServerThread extends Thread{
private String sendIP = "127.0.0.1";
private int sendPORT = 6666;
private int receivePORT = 8888;
//声明发送信息的数据报套结字
private DatagramSocket sendSocket = null;
//声明发送信息的数据包
private DatagramPacket sendPacket = null;
//声明接受信息的数据报套结字
private DatagramSocket receiveSocket = null;
//声明接受信息的数据报
private DatagramPacket receivePacket = null;
//收发数据的端口
private int myPort = 0;
//接收数据主机的IP地址
private String friendIP = null;
private int friendPort = 0;
//缓冲数组的大小
public static final int BUFFER_SIZE = 5120;
private byte inBuf[] = null; //接收数据的缓冲数组
private byte outBuf[] = null; //发送数据的缓冲数组
JTextArea jta;
// 构造函数
public ClientToServerThread(JTextArea jta) {
this.jta = jta;
getPropertiesInfo();
}
public void run() {
String receiveInfo = "";
try{
inBuf = new byte[BUFFER_SIZE];
receivePacket = new DatagramPacket(inBuf,inBuf.length);
receiveSocket = new DatagramSocket(receivePORT);
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
while (true) {
if(receiveSocket == null){
break;
} else {
try {
receiveSocket.receive(receivePacket);
String message = new String(receivePacket.getData(),0,receivePacket.getLength());
jta.append("收到数据"+message+"\n");
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
}
}
/**
* 该方法用来获得服务器属性文件中的IP、PORT
*/
private void getPropertiesInfo(){
Properties prop = new Properties();
InputStream inStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("ServerInfo.properties");
try{
//获得相应的键值对
prop.load(inStream);
}catch(IOException e){
e.printStackTrace();
}
//根据相应的键获得对应的值
receivePORT = Integer.parseInt(prop.getProperty("serverudp.port"));
}
public void sendData(byte buffer[]){
try{
InetAddress address = InetAddress.getByName(sendIP);
//outBuf = new byte[BUFFER_SIZE];
sendPacket = new DatagramPacket(buffer,buffer.length,address,sendPORT);
sendSocket = new DatagramSocket();
sendSocket.send(sendPacket);
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
public void closeSocket(){
receiveSocket.close();
}
}
运行截图:
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例为大家分享了java使用udp模式编写聊天程序的具体代码,供大家参考,具体内容如下java代码:?123456789101112131415161718
Erlang中gen_tcp用于编写TCP程序,gen_udp用于编写UDP程序。一个简单的TCP服务器echo示例:复制代码代码如下:Start_echo_s
本文实例为大家分享了Java实现UDP互发消息的具体代码,供大家参考,具体内容如下UDP的发送端packageudp;/**UDP发送端*/importjava
本文实例为大家分享了java利用udp实现发送数据的具体代码,供大家参考,具体内容如下1.udp的特点数据以包的形式发送数据udp是面向无连接的udp会丢失数据
聊天器简易版使用udp实现一个简单的聊天器程序,要求如下:•在一个电脑中编写1个程序,有2个功能•1.获取键盘数据,并将其发送给对方&#