java开发聊天功能用什么技术实现的?

java开发聊天功能用什么技术实现的?,第1张

Java开发聊天功衫纤能可以使用多种技术来实现,以下是其中薯塌吵一些常用的技术:

Socket编程:使用Java的Socket API,通过TCP/IP协议实现网络通信,建立客户端和服务端之间的连接,实现聊天功能

Java NIO:使用Java NIO(New IO)库,通过Channel和Buffer的概念实现非阻塞IO,提高网络通信的性能和效率,从而实现聊天功能。

WebSocket:使用Java WebSocket API,通过WebSocket协议实现全双工通信,建立WebSocket连接,实现实时聊天功能。

RESTful API:使用Java RESTful API,通过HTTP协议实现客户端和服务端之数侍间的通信,实现聊天功能。

第三方库或框架:使用第三方库或框架,如Netty、Apache MINA、Smack等,提供了更高级别的抽象和更简单易用的接口,简化了开发聊天功能的难度。

以上技术都可以用于实现Java开发的聊天功能,具体选择哪种技术取决于实际的需求和情况。

/**

* 基于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()

}

}

}

这个是客户端

import java.net.*

import java.io.*

import java.awt.*

import java.awt.event.*

public class client extends Frame implements ActionListener{

int i=1Frame f

TextField ip,port

Label Lip,Lport

Button connect,exit

public static void main(String args[])

{client c1 = new client()

c1.init()

}

public void init()

{

f=new Frame("client connection")

f.setLayout(new FlowLayout())

ip =new TextField("localhost")

port =new TextField("8189",5)

Lip=new Label("ip address")

Lport=new Label("port")

connect=new Button("connect")

exit=new Button("exit")

connect.addActionListener(this)

exit.addActionListener(this)

f.add(Lip)

f.add(ip)

f.add(Lport)

f.add(port)

f.add(connect)

f.add(exit)

f.setSize(500,60)

f.setVisible(true)

}

public void actionPerformed(ActionEvent e){

if(e.getSource()==exit)

System.exit(0)

if(e.getSource()==connect)

{

new Thread(new threadclient(ip.getText(),port.getText(),i)).start()

i++

}

}

}

class threadclient extends Frame implements Runnable,ActionListener{

String ip,port

int no

Frame f

TextArea ta

TextArea name

TextField tf

Button send,bye

InputStream ins

Socket s

PrintStream out1

BufferedReader in

BufferedWriter out

threadclient(String n,String m,int i)

{

ip=n

port=m

no=i

}

public void run(){

f=new Frame("client NO." +no)

f.setLayout(new FlowLayout())

ta=new TextArea("",10,30,TextArea.SCROLLBARS_BOTH)

tf=new TextField("",20)

send=new Button("send")

bye=new Button("bye")

send.addActionListener(this)

bye.addActionListener(this)

f.add(ta)

f.add(tf)

f.add(send)

f.add(bye)

f.setSize(300,300)

f.setVisible(true)

Integer tmp=new Integer(port)

int portint =tmp.intValue()

try

{

s=new Socket(ip,portint)

in=new BufferedReader(new InputStreamReader(s.getInputStream()))

out1=new PrintStream(s.getOutputStream())

ta.append(in.readLine()+"\n")

}catch(Exception e)

{

System.out.println(e.getMessage()+" ss")

}

}

public void send(String txt){

try{

out1.println(txt)

out1.flush()

ta.append(in.readLine()+"\n")

}catch(IOException e)

{

System.out.println(e.getMessage()+"send")

}

}

public void actionPerformed(ActionEvent e){

if(e.getSource()==bye){

send("BYE")

System.exit(0)

}

if (e.getSource()==send)

send(tf.getText())

}

}

这个是服务器

import java.awt.Button

import java.awt.FlowLayout

import java.awt.Frame

import java.awt.TextArea

import java.awt.TextField

import java.awt.event.ActionEvent

import java.awt.event.ActionListener

import java.io.*

import java.io.*

import java.net.ServerSocket

import java.net.Socket

import java.util.HashMap

import java.util.Map

public class server {

private static Map<String,Socket>clientMap=new HashMap<String,Socket>()

public static void main(String[] args) {

int i = 1

try {

ServerSocket s = new ServerSocket(8189)

for () {

Socket incoming = s.accept()

System.out.println("连接成功" + i)

ThreadedEchoHandler teh=new ThreadedEchoHandler(incoming, i)

teh.start()

String name=teh.getClientname()

clientMap.put(name,incoming)

i++

}

} catch (Exception e) {

System.out.println(e)

}

}

}

class ThreadedEchoHandler extends Thread {

Frame f

TextArea ta

TextField tf

Button send, bye

InputStream ins

Socket s

PrintStream out1

BufferedReader in

PrintWriter out

public ThreadedEchoHandler(Socket i, int c) {

incoming = i

counter = c

f=new Frame("server")

f.setLayout(new FlowLayout())

ta=new TextArea("",10,30,TextArea.SCROLLBARS_BOTH)

tf=new TextField("",20)

send=new Button("send")

bye=new Button("bye")

send.addActionListener(new ActionListener(){

@Override

public void actionPerformed(ActionEvent arg0) {

send(tf.getText())

}

})

bye.addActionListener(new ActionListener(){

@Override

public void actionPerformed(ActionEvent arg0) {

send("bye")

}

})

f.add(ta)

f.add(tf)

f.add(send)

f.add(bye)

f.setSize(300,300)

f.setVisible(true)

}

public String getClientname() {

try {

in = new BufferedReader(new InputStreamReader(

incoming.getInputStream()))

out = new PrintWriter(incoming.getOutputStream(), true)

return in.readLine()

} catch (IOException e) {

System.out.println(e.getMessage()+"get")

}

return null

}

public void send(String context){

out.println(context)

out.flush()

}

public void run() {

try {

boolean done = false

while (!done) {

String str = in.readLine()

if (str == null)

done = true

else {

out.println("Echo(" + counter + "):" + str)

ta.append("Echo(" + counter + "):" + str+"\n")

if (str.trim().equals("BYE"))

done = true

}

}

incoming.close()

} catch (Exception e) {

System.out.println(e.getMessage()+"run")

}

}

private Socket incoming

private int counter

}

这个鸟东西是个新手写的。唉,太烂了,我无力吐槽。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/8230189.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-14
下一篇 2023-04-14

发表评论

登录后才能评论

评论列表(0条)

保存