十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
/**
网站建设哪家好,找成都创新互联公司!专注于网页设计、网站建设、微信开发、重庆小程序开发公司、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了开江免费建站欢迎大家使用!
* 基于UDP协议的聊天程序
*
* 2007.9.18
* */
//导入包
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;
public class Chat extends JFrame implements ActionListener
{
//广播地址或者对方的地址
public static final String sendIP = "172.18.8.255";
//发送端口9527
public static final int sendPort = 9527;
JPanel p = new JPanel();
List lst = new List(); //消息显示
JTextField txtIP = new JTextField(18); //填写IP地址
JTextField txtMSG = new JTextField(20); //填写发送消息
JLabel lblIP = new JLabel("IP地址:");
JLabel lblMSG = new JLabel("消息:");
JButton btnSend = new JButton("发送");
byte [] buf;
//定义DatagramSocket的对象必须进行异常处理
//发送和接收数据报包的套接字
DatagramSocket ds = null;
//=============构造函数=====================
public Chat()
{
CreateInterFace();
//注册消息框监听器
txtMSG.addActionListener(this);
btnSend.addActionListener(this);
try
{
//端口:9527
ds =new DatagramSocket(sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
//============接受消息============
//匿名类
new Thread(new Runnable()
{
public void run()
{
byte buf[] = new byte[1024];
//表示接受数据报包
while(true)
{
try
{
DatagramPacket dp = new DatagramPacket(buf,1024,InetAddress.getByName(txtIP.getText()),sendPort);
ds.receive(dp);
lst.add("【消息来自】◆" + dp.getAddress().getHostAddress() + "◆"+"【说】:" + new String (buf,0,dp.getLength()) /*+ dp.getPort()*/,0);
}
catch(Exception e)
{
if(ds.isClosed())
{
e.printStackTrace();
}
}
}
}
}).start();
//关闭窗体事件
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.out.println("test");
int n=JOptionPane.showConfirmDialog(null,"是否要退出?","退出",JOptionPane.YES_NO_OPTION);
if(n==JOptionPane.YES_OPTION)
{
dispose();
System.exit(0);
ds.close();//关闭ds对象//关闭数据报套接字
}
}
});
}
//界面设计布局
public void CreateInterFace()
{
this.add(lst,BorderLayout.CENTER);
this.add(p,BorderLayout.SOUTH);
p.add(lblIP);
p.add(txtIP);
p.add(lblMSG);
p.add(txtMSG);
p.add(btnSend);
txtIP.setText(sendIP);
//背景颜色
lst.setBackground(Color.yellow);
//JAVA默认风格
this.setUndecorated(true);
this.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
this.setSize(600,500);
this.setTitle("〓聊天室〓");
this.setResizable(false);//不能改变窗体大小
this.setLocationRelativeTo(null);//窗体居中
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(true);
txtMSG.requestFocus();//消息框得到焦点
}
//===============================Main函数===============================
public static void main(String[]args)
{
new Chat();
}
//================================发送消息===============================
//消息框回车发送消息事件
public void actionPerformed(ActionEvent e)
{
//得到文本内容
buf = txtMSG.getText().getBytes();
//判断消息框是否为空
if (txtMSG.getText().length()==0)
{
JOptionPane.showMessageDialog(null,"发送消息不能为空","提示",JOptionPane.WARNING_MESSAGE);
}
else{
try
{
InetAddress address = InetAddress.getByName(sendIP);
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
ds.send(dp);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
txtMSG.setText("");//清空消息框
//点发送按钮发送消息事件
if(e.getSource()==btnSend)
{
buf = txtMSG.getText().getBytes();
try
{
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
txtMSG.setText("");//清空消息框
txtMSG.requestFocus();
}
}
}
前天帮人解决过,代码如下:public class iChat extends JFrame {
private JPanel jContentPane;
private JButton jButton1;
private JScrollPane jScrollPane1;
private JTextArea jTextArea1,jTextArea2; public iChat() {
super();
initialize();
} private void initialize() {
this.setSize(375, 364);
jTextArea1 = getJTextArea1();
this.setContentPane(getJContentPane());
this.setTitle("聊天室");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setBackground(Color.BLUE);//蓝色为JPanel 。
jContentPane.setLayout(null);
jContentPane.add(getJButton1(), null);
jContentPane.add(getJTextArea2(), null);
jContentPane.add(getJScrollPane1(), null);
}
return jContentPane;
} private JTextArea getJTextArea2() {
if (jTextArea2 == null) {
jTextArea2 = new JTextArea();
jTextArea2.setBounds(new Rectangle(1, 253, 282, 73));
jTextArea2.setLineWrap(true);
jTextArea2.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
String s = "你说:" + jTextArea2.getText();
String date = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss").format(Calendar
.getInstance().getTime());
jTextArea1.append(date + "\n");
jTextArea1.append(s);
}
}
});
}
return jTextArea2;
} private JButton getJButton1() {
if (jButton1 == null) {
jButton1 = new JButton();
jButton1.setBounds(new Rectangle(293, 288, 62, 32));
jButton1.setText("发送");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
String s = "你说:" + jTextArea2.getText();
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(Calendar.getInstance().getTime());
jTextArea1.append(date + "\n");
jTextArea1.append(s + "\n");
jTextArea2.setText(""); }
});
}
return jButton1;
}
private JScrollPane getJScrollPane1() {
if (jScrollPane1 == null) {
jScrollPane1 = new JScrollPane();
jScrollPane1.setBounds(new Rectangle(0, 0, 360, 220));
jScrollPane1.setViewportView(getJTextArea1());
}
return jScrollPane1;
} private JTextArea getJTextArea1() {
if (jTextArea1 == null) {
jTextArea1 = new JTextArea();
jTextArea1.setEditable(false);
jTextArea1.setLineWrap(true);
}
return jTextArea1;
} public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
iChat thisClass = new iChat();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
}
});
}}
【ClientSocketDemo.java 客户端Java源代码】
import java.net.*;
import java.io.*;
public class ClientSocketDemo
{
//声明客户端Socket对象socket
Socket socket = null;
//声明客户器端数据输入输出流
DataInputStream in;
DataOutputStream out;
//声明字符串数组对象response,用于存储从服务器接收到的信息
String response[];
//执行过程中,没有参数时的构造方法,本地服务器在本地,取默认端口10745
public ClientSocketDemo()
{
try
{
//创建客户端socket,服务器地址取本地,端口号为10745
socket = new Socket("localhost",10745);
//创建客户端数据输入输出流,用于对服务器端发送或接收数据
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//获取客户端地址及端口号
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
//向服务器发送数据
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
//从服务器接收数据
response = new String[3];
for (int i = 0; i response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//执行过程中,有一个参数时的构造方法,参数指定服务器地址,取默认端口10745
public ClientSocketDemo(String hostname)
{
try
{
//创建客户端socket,hostname参数指定服务器地址,端口号为10745
socket = new Socket(hostname,10745);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; i response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//执行过程中,有两个个参数时的构造方法,第一个参数hostname指定服务器地址
//第一个参数serverPort指定服务器端口号
public ClientSocketDemo(String hostname,String serverPort)
{
try
{
socket = new Socket(hostname,Integer.parseInt(serverPort));
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; i response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
String comd[] = args;
if(comd.length == 0)
{
System.out.println("Use localhost(127.0.0.1) and default port");
ClientSocketDemo demo = new ClientSocketDemo();
}
else if(comd.length == 1)
{
System.out.println("Use default port");
ClientSocketDemo demo = new ClientSocketDemo(args[0]);
}
else if(comd.length == 2)
{
System.out.println("Hostname and port are named by user");
ClientSocketDemo demo = new ClientSocketDemo(args[0],args[1]);
}
else System.out.println("ERROR");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
【ServerSocketDemo.java 服务器端Java源代码】
import java.net.*;
import java.io.*;
public class ServerSocketDemo
{
//声明ServerSocket类对象
ServerSocket serverSocket;
//声明并初始化服务器端监听端口号常量
public static final int PORT = 10745;
//声明服务器端数据输入输出流
DataInputStream in;
DataOutputStream out;
//声明InetAddress类对象ip,用于获取服务器地址及端口号等信息
InetAddress ip = null;
//声明字符串数组对象request,用于存储从客户端发送来的信息
String request[];
public ServerSocketDemo()
{
request = new String[3]; //初始化字符串数组
try
{
//获取本地服务器地址信息
ip = InetAddress.getLocalHost();
//以PORT为服务端口号,创建serverSocket对象以监听该端口上的连接
serverSocket = new ServerSocket(PORT);
//创建Socket类的对象socket,用于保存连接到服务器的客户端socket对象
Socket socket = serverSocket.accept();
System.out.println("This is server:"+String.valueOf(ip)+PORT);
//创建服务器端数据输入输出流,用于对客户端接收或发送数据
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//接收客户端发送来的数据信息,并显示
request[0] = in.readUTF();
request[1] = in.readUTF();
request[2] = in.readUTF();
System.out.println("Received messages form client is:");
System.out.println(request[0]);
System.out.println(request[1]);
System.out.println(request[2]);
//向客户端发送数据
out.writeUTF("Hello client!");
out.writeUTF("Your ip is:"+request[1]);
out.writeUTF("Your port is:"+request[2]);
}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
ServerSocketDemo demo = new ServerSocketDemo();
}
}
实现java语音聊天室的方法很简单,要么自己从零研发,要么直接使用别人的成品,意思是找网上的第三方,他们自己有研发产品的。建议考虑ZEGO即构科技,他们的语聊房SDK很好用的,提供低延迟和低成本的方案供选择,在保障语音质量的前提下,码率最低可到8kbps,可以试试。