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

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

1 Socket编程:使用Socket可以在客户端和服务器之间建立TCP连接,实现双方之间的实时通信。Java提供了Socket类和ServerSocket类,可用于实现Socket编程。

2 WebSocket:WebSocket是一种基于TCP协议的新型网络通信协议,它可以在浏览器和服务器之间建立持久连接,实现双向实时通信。Java可以使用一些WebSocket框架,如Netty、Tomcat等,来实现WebSocket功能。

3 >

你说的我明白。如果真正使用alohal协议的时候,所有的机器都可以检测网络电平变化的是吧?但是使用Java编写模拟程序的话,我们并不能可能检测电平的变换,只能通过一定的手段来模拟这个过程。如果你将一个包裹群发,这样所有的机器都可以接受这个包,这样就可以做到所有机器模拟检测电平变化的这个要求。我认为这个是最有说服力的模拟方法了。

线程需要使用Thread类型,重写里面的run函数,调用start()启动线程,具体可以搜索一把Thread,例子遍地都是。

UDP协议使用Socket类型,初始化的时候参数里面绑定(或者初始化好以后直接调用bind绑定端口,一般输出不用绑定,监听的时候需要绑定)。调用里面的getOutputStream得到输入流。调用getInputStream得到输入流。

OutputStream:输出流,用于向网络中输出数据。调用其中的write函数进行输出,函数的参数就是输出的byte数组。

InputStream: 输入流,用于接受网络里面的数据。调用其中的read可以得到输入的包。

String:你要输出的字符串,调用里面的getBytes可以得到String的byte数组。

其它的应该用不到什么了吧。

1发送字符串的话用byte[]就可以啊。用Socket类里面的getOutputStream可以获得一个发送数据的OutputStream类对象。这个类对象有一个函数write(byte[] b) 可以向网络写byte[]。一个字符串可以通过String类中的getBytes() 转化成byte[]。这样总该明白了吧

2说一下我的思路:开一个端口A发送UDP包(广播给端口B),用于模拟发送,用一个线程(线程1)来跑。开端口B接受局域网内的包,用另外一个线程(线程2)来跑。在发送UDP包的时候,将变量mark置1,发送完置0。线程2如果接受到一个不是从本机发送的包,而且此时mark是1(说明本机和另外一个机器同时在发包),发生了冲突,表示线程1这次发送的包失败。

这个时比较简单的。

package QQ;

import javanet;

import javaio;

import javasql;

import javautil;

public class QQServer {

public static void main(String args[]) {

try {

HashMap<String , Socket> hm = new

HashMap<String , Socket>() ;

// 服务器到8000端口监听(1)

ServerSocket ss = new ServerSocket

(8000);

while (true) {

Systemoutprintln("服务器正在

8000端口监听");

Socket s = ssaccept();

MyService t = new MyService();

tsetSocket(s) ;

tsetHashMap(hm) ;

tstart();

}

} catch (Exception e) {

eprintStackTrace();

}

}

}

class MyService extends Thread {

private Socket s ;

private HashMap<String , Socket> hm ;

public void setHashMap(HashMap<String , Socket> hm){

thishm = hm ;

}

public void setSocket(Socket s){

thiss = s ;

}

public void run() {

try {

// 接收客户端发送来的用户名和密码(2)

InputStream is = sgetInputStream();

InputStreamReader isr = new InputStreamReader

(is);

BufferedReader br = new BufferedReader(isr);

String uandp = brreadLine();

// 拆分用户名和密码(4)

String u = "";

String p = "";

try{

u = uandpsplit("%")[0];

p = uandpsplit("%")[1];

}catch(Exception e){}

// 到数据库中验证(5)

ClassforName

("commicrosoftjdbcsqlserverSQLServerDriver");

Connection cn = DriverManager

getConnection(

"jdbc:microsoft:sqlserver://127001:1433;databasename=qq2",

"sa", "123");

PreparedStatement ps = cn

prepareStatement("select

username from username where username= and password=");

pssetString(1, u);

pssetString(2, p);

ResultSet rs = psexecuteQuery();

// 发送确认信息到客户端(7)

OutputStream os = sgetOutputStream();

OutputStreamWriter osw = new

OutputStreamWriter(os);

PrintWriter pw = new PrintWriter(osw, true);

if (rsnext()) {

pwprintln("ok");

//将自己的名字发送给HashMap中的其他人

(13)

for(Socket ts : hmvalues()){

OutputStream tos =

tsgetOutputStream() ;

OutputStreamWriter tosw = new

OutputStreamWriter(tos) ;

PrintWriter tpw = new

PrintWriter(tosw , true) ;

tpwprintln("user%"+u) ;

}

//将其他人的名字发送给自己(13)

for(String tu : hmkeySet()){

pwprintln("user%"+tu) ;

}

//将用户名和对应的Socket存入HashMap

(13)

hmput(u, s) ;

// 接收客户端发送来的信息(11)

while (true) {

String message = brreadLine

();

if(messageequals("exit")){

for(Socket ts :

hmvalues()){

OutputStream

tos = tsgetOutputStream() ;

OutputStreamWriter tosw = new OutputStreamWriter(tos) ;

PrintWriter

tpw = new PrintWriter(tosw , true) ;

tpwprintln

("exit%"+u);

}

hmremove(u);

}

String to = messagesplit

("%")[0];

String mess = messagesplit

("%")[1];

Socket ts = hmget(to);

OutputStream tos =

tsgetOutputStream();

OutputStreamWriter tosw = new

OutputStreamWriter(tos);

PrintWriter tpw = new

PrintWriter(tosw, true);

tpwprintln("mess%"+mess

+"\n");

Systemoutprintln(message);

}

} else {

pwprintln("err");

}

} catch (Exception e) {}

}

}

聊天程序又叫即时通讯系统

分类两部分:客户端和服务端

客户端:用户聊天的界面

服务端:接收消息并转发到指定用户

其中服务端和客户端用tcp或者udp连接,使用socket编程完成通信。

按着这个思路可以开发出一套聊天程序

客户端常用界面 bs版本的又layim

服务端 openfire或者自己实现

这个是客户端

import javanet;

import javaio;

import javaawt;

import javaawtevent;

public class client extends Frame implements ActionListener{

int i=1;Frame f;

TextField ip,port;

Label Lip,Lport;

Button connect,exit;

public static void main(String args[])

{client c1 = new client();

c1init();

}

public void init()

{

f=new Frame("client connection");

fsetLayout(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");

connectaddActionListener(this);

exitaddActionListener(this);

fadd(Lip);

fadd(ip);

fadd(Lport);

fadd(port);

fadd(connect);

fadd(exit);

fsetSize(500,60);

fsetVisible(true);

}

public void actionPerformed(ActionEvent e){

if(egetSource()==exit)

Systemexit(0);

if(egetSource()==connect)

{

new Thread(new threadclient(ipgetText(),portgetText(),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);

fsetLayout(new FlowLayout());

ta=new TextArea("",10,30,TextAreaSCROLLBARS_BOTH);

tf=new TextField("",20);

send=new Button("send");

bye=new Button("bye");

sendaddActionListener(this);

byeaddActionListener(this);

fadd(ta);

fadd(tf);

fadd(send);

fadd(bye);

fsetSize(300,300);

fsetVisible(true);

Integer tmp=new Integer(port);

int portint =tmpintValue();

try

{

s=new Socket(ip,portint);

in=new BufferedReader(new InputStreamReader(sgetInputStream()));

out1=new PrintStream(sgetOutputStream());

taappend(inreadLine()+"\n");

}catch(Exception e)

{

Systemoutprintln(egetMessage()+" ss");

}

}

public void send(String txt){

try{

out1println(txt);

out1flush();

taappend(inreadLine()+"\n");

}catch(IOException e)

{

Systemoutprintln(egetMessage()+"send");

}

}

public void actionPerformed(ActionEvent e){

if(egetSource()==bye){

send("BYE");

Systemexit(0);

}

if (egetSource()==send)

send(tfgetText());

}

}

这个是服务器

import javaawtButton;

import javaawtFlowLayout;

import javaawtFrame;

import javaawtTextArea;

import javaawtTextField;

import javaawteventActionEvent;

import javaawteventActionListener;

import javaio;

import javaio;

import javanetServerSocket;

import javanetSocket;

import javautilHashMap;

import javautilMap;

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 = saccept();

Systemoutprintln("连接成功" + i);

ThreadedEchoHandler teh=new ThreadedEchoHandler(incoming, i);

tehstart();

String name=tehgetClientname();

clientMapput(name,incoming);

i++;

}

} catch (Exception e) {

Systemoutprintln(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");

fsetLayout(new FlowLayout());

ta=new TextArea("",10,30,TextAreaSCROLLBARS_BOTH);

tf=new TextField("",20);

send=new Button("send");

bye=new Button("bye");

sendaddActionListener(new ActionListener(){

@Override

public void actionPerformed(ActionEvent arg0) {

send(tfgetText());

}

});

byeaddActionListener(new ActionListener(){

@Override

public void actionPerformed(ActionEvent arg0) {

send("bye");

}

});

fadd(ta);

fadd(tf);

fadd(send);

fadd(bye);

fsetSize(300,300);

fsetVisible(true);

}

public String getClientname() {

try {

in = new BufferedReader(new InputStreamReader(

incominggetInputStream()));

out = new PrintWriter(incominggetOutputStream(), true);

return inreadLine();

} catch (IOException e) {

Systemoutprintln(egetMessage()+"get");

}

return null;

}

public void send(String context){

outprintln(context);

outflush();

}

public void run() {

try {

boolean done = false;

while (!done) {

String str = inreadLine();

if (str == null)

done = true;

else {

outprintln("Echo(" + counter + "):" + str);

taappend("Echo(" + counter + "):" + str+"\n");

if (strtrim()equals("BYE"))

done = true;

}

}

incomingclose();

} catch (Exception e) {

Systemoutprintln(egetMessage()+"run");

}

}

private Socket incoming;

private int counter;

}

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

给你一个简单的实现吧,注意一定要先运行MyServerjava

//MyCilentjava

import javaio;

import javanet;

import javaxswing;

import javaawt;

import javaawtevent;

public class MyClient extends JFrame implements ActionListener{

JTextField tf;

JTextArea tx;

JButton bt;

PrintWriter out;

public MyClient(){

tf=new JTextField(20);

tx=new JTextArea();

txsetLineWrap(true);

txsetWrapStyleWord(true);

JPanel pan=new JPanel();

JScrollPane jsp=new JScrollPane(tx);

add(jsp,"Center");

bt=new JButton("SEND");

btaddActionListener(this);

panadd(tf);

panadd(bt);

add(pan,"South");

thisaddWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

Systemexit(0);

}

});

setTitle("THE CLIENT");

setSize(400,300);

setVisible(true);

try{

Socket socket=new Socket("127001",1680);

out=new PrintWriter(socketgetOutputStream(),true);

InputStreamReader in = new InputStreamReader(socketgetInputStream());

BufferedReader sin=new BufferedReader(in);

String s;

while(true){

s=sinreadLine();

txappend("#Server Said#: "+s+"\n");

}

}catch(Exception e){

eprintStackTrace();

}

}

public void actionPerformed(ActionEvent e){

if(egetSource()==bt){

txappend("@Client Said@: "+tfgetText()+"\n");

outprintln(tfgetText());

tfsetText("");

}

}

public static void main(String[] args){

MyClient mct = new MyClient();

}

}

//MyServerjava

import javaio;

import javanet;

import javaxswing;

import javaawt;

import javaawtevent;

public class MyServer extends JFrame implements ActionListener{

JTextField tf;

JTextArea tx;

JButton bt;

JScrollPane jsp;

JPanel pan;

PrintWriter out;

public MyServer(){

tx=new JTextArea();

txsetLineWrap(true);

txsetWrapStyleWord(true);

jsp=new JScrollPane(tx);

tf=new JTextField(20);

bt=new JButton("SEND");

btaddActionListener(this);

pan=new JPanel();

panadd(tf);

panadd(bt);

add(pan,"South");

add(jsp,"Center");

thisaddWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

Systemexit(0);

}

});

setTitle("THE SERVER");

setSize(400,300);

setVisible(true);

try{

ServerSocket server = new ServerSocket(1680);

Socket socket = serveraccept();

InputStreamReader in = new InputStreamReader(socketgetInputStream());

BufferedReader sin=new BufferedReader(in);

out=new PrintWriter(socketgetOutputStream(),true);

while(true){

String s=sinreadLine();

txappend("@Client Said@: "+s+"\n");

}

}catch(Exception e){

eprintStackTrace();

}

}

public void actionPerformed(ActionEvent e){

if(egetSource()==bt){

String st = tfgetText();

txappend("#Server Said#: "+st+"\n");

outprintln(st);

tfsetText("");

}

}

public static void main(String[] args){

MyServer msr = new MyServer();

}

}

共四个java文件,源代码如下:

import javaawt;

import javanet;

import javaawtevent;

import javaio;

import javautilHashtable;

public class ChatArea extends Panel implements ActionListener,Runnable

{

Socket socket=null;

DataInputStream in=null;

DataOutputStream out=null;

Thread threadMessage=null;

TextArea 谈话显示区,私聊显示区=null;

TextField 送出信息=null;

Button 确定,刷新谈话区,刷新私聊区;

Label 提示条=null;

String name=null;

Hashtable listTable;

List listComponent=null;

Choice privateChatList;

int width,height;

public ChatArea(String name,Hashtable listTable,int width,int height)

{

setLayout(null);

setBackground(Colororange);

thiswidth=width;

thisheight=height;

setSize(width,height);

thislistTable=listTable;

thisname=name;

threadMessage=new Thread(this);

谈话显示区=new TextArea(10,10);

私聊显示区=new TextArea(10,10);

确定=new Button("送出信息到:");

刷新谈话区=new Button("刷新谈话区");

刷新私聊区=new Button("刷新私聊区");

提示条=new Label("双击聊天者可私聊",LabelCENTER);

送出信息=new TextField(28);

确定addActionListener(this);

送出信息addActionListener(this);

刷新谈话区addActionListener(this);

刷新私聊区addActionListener(this);

listComponent=new List();

listComponentaddActionListener(this);

privateChatList=new Choice();

privateChatListadd("大家()");

privateChatListselect(0);

add(谈话显示区);

谈话显示区setBounds(10,10,(width-120)/2,(height-120));

add(私聊显示区);

私聊显示区setBounds(10+(width-120)/2,10,(width-120)/2,(height-120));

add(listComponent);

listComponentsetBounds(10+(width-120),10,100,(height-160));

add(提示条);

提示条setBounds(10+(width-120),10+(height-160),110,40);

Panel pSouth=new Panel();

pSouthadd(送出信息);

pSouthadd(确定);

pSouthadd(privateChatList);

pSouthadd(刷新谈话区);

pSouthadd(刷新私聊区);

add(pSouth);

pSouthsetBounds(10,20+(height-120),width-20,60);

}

public void setName(String s)

{

name=s;

}

public void setSocketConnection(Socket socket,DataInputStream in,DataOutputStream out)

{

thissocket=socket;

thisin=in;

thisout=out;

try

{

threadMessagestart();

}

catch(Exception e)

{

}

}

public void actionPerformed(ActionEvent e)

{

if(egetSource()==确定||egetSource()==送出信息)

{

String message="";

String people=privateChatListgetSelectedItem();

people=peoplesubstring(0,peopleindexOf("("));

message=送出信息getText();

if(messagelength()>0)

{

try {

if(peopleequals("大家"))

{

outwriteUTF("公共聊天内容:"+name+"说:"+message);

}

else

{

outwriteUTF("私人聊天内容:"+name+"悄悄地说:"+message+"#"+people);

}

}

catch(IOException event)

{

}

}

}

else if(egetSource()==listComponent)

{

privateChatListinsert(listComponentgetSelectedItem(),0);

privateChatListrepaint();

}

else if(egetSource()==刷新谈话区)

{

谈话显示区setText(null);

}

else if(egetSource()==刷新私聊区)

{

私聊显示区setText(null);

}

}

public void run()

{

while(true)

{

String s=null;

try

{

s=inreadUTF();

if(sstartsWith("聊天内容:"))

{

String content=ssubstring(sindexOf(":")+1);

谈话显示区append("\n"+content);

}

if(sstartsWith("私人聊天内容:"))

{

String content=ssubstring(sindexOf(":")+1);

私聊显示区append("\n"+content);

}

else if(sstartsWith("聊天者:"))

{

String people=ssubstring(sindexOf(":")+1,sindexOf("性别"));

String sex=ssubstring(sindexOf("性别")+2);

listTableput(people,people+"("+sex+")");

listComponentadd((String)listTableget(people));

listComponentrepaint();

}

else if(sstartsWith("用户离线:"))

{

String awayPeopleName=ssubstring(sindexOf(":")+1);

listComponentremove((String)listTableget(awayPeopleName));

listComponentrepaint();

谈话显示区append("\n"+(String)listTableget(awayPeopleName)+"离线");

listTableremove(awayPeopleName);

}

Threadsleep(5);

}

catch(IOException e)

{

listComponentremoveAll();

listComponentrepaint();

listTableclear();

谈话显示区setText("和服务器的连接已中断\n必须刷新浏览器才能再次聊天");

break;

}

catch(InterruptedException e)

{

}

}

}

}

ChatServerjava

import javaio;

import javanet;

import javautil;

public class ChatServer

{

public static void main(String args[])

{

ServerSocket server=null;

Socket you=null;

Hashtable peopleList;

peopleList=new Hashtable();

while(true)

{

try

{

server=new ServerSocket(6666);

}

catch(IOException e1)

{

Systemoutprintln("正在监听");

}

try {

you=serveraccept();

InetAddress address=yougetInetAddress();

Systemoutprintln("用户的IP:"+address);

}

catch (IOException e)

{

}

if(you!=null)

{

Server_thread peopleThread=new Server_thread(you,peopleList);

peopleThreadstart();

}

else {

continue;

}

}

}

}

class Server_thread extends Thread

{

String name=null,sex=null;

Socket socket=null;

File file=null;

DataOutputStream out=null;

DataInputStream in=null;

Hashtable peopleList=null;

Server_thread(Socket t,Hashtable list)

{

peopleList=list;

socket=t;

try {

in=new DataInputStream(socketgetInputStream());

out=new DataOutputStream(socketgetOutputStream());

}

catch (IOException e)

{

}

}

public void run()

{

while(true)

{ String s=null;

try

{

s=inreadUTF();

if(sstartsWith("姓名:"))

{

name=ssubstring(sindexOf(":")+1,sindexOf("性别"));

sex=ssubstring(slastIndexOf(":")+1);

boolean boo=peopleListcontainsKey(name);

if(boo==false)

{

peopleListput(name,this);

outwriteUTF("可以聊天:");

Enumeration enum=peopleListelements();

while(enumhasMoreElements())

{

Server_thread th=(Server_thread)enumnextElement();

thoutwriteUTF("聊天者:"+name+"性别"+sex);

if(th!=this)

{

outwriteUTF("聊天者:"+thname+"性别"+thsex);

}

}

}

else

{

outwriteUTF("不可以聊天:");

}

}

else if(sstartsWith("公共聊天内容:"))

{

String message=ssubstring(sindexOf(":")+1);

Enumeration enum=peopleListelements();

while(enumhasMoreElements())

{

((Server_thread)enumnextElement())outwriteUTF("聊天内容:"+message);

}

}

else if(sstartsWith("用户离开:"))

{

Enumeration enum=peopleListelements();

while(enumhasMoreElements())

{ try

{

Server_thread th=(Server_thread)enumnextElement();

if(th!=this&&thisAlive())

{

thoutwriteUTF("用户离线:"+name);

}

}

catch(IOException eee)

{

}

}

peopleListremove(name);

socketclose();

Systemoutprintln(name+"用户离开了");

break;

}

else if(sstartsWith("私人聊天内容:"))

{

String 悄悄话=ssubstring(sindexOf(":")+1,sindexOf("#"));

String toPeople=ssubstring(sindexOf("#")+1);

Server_thread toThread=(Server_thread)peopleListget(toPeople);

if(toThread!=null)

{

toThreadoutwriteUTF("私人聊天内容:"+悄悄话);

}

else

{

outwriteUTF("私人聊天内容:"+toPeople+"已经离线");

}

}

}

catch(IOException ee)

{

Enumeration enum=peopleListelements();

while(enumhasMoreElements())

{ try

{

Server_thread th=(Server_thread)enumnextElement();

if(th!=this&&thisAlive())

{

thoutwriteUTF("用户离线:"+name);

}

}

catch(IOException eee)

{

}

}

peopleListremove(name);

try

{

socketclose();

}

catch(IOException eee)

{

}

Systemoutprintln(name+"用户离开了");

break;

}

}

}

}

import javaawt;

import javaio;

import javanet;

import javaapplet;

import javautilHashtable;

ClientChatjava

public class ClientChat extends Applet implements Runnable

{

Socket socket=null;

DataInputStream in=null;

DataOutputStream out=null;

InputNameTextField 用户提交昵称界面=null;

ChatArea 用户聊天界面=null;

Hashtable listTable;

Label 提示条;

Panel north, center;

Thread thread;

public void init()

{

int width=getSize()width;

int height=getSize()height;

listTable=new Hashtable();

setLayout(new BorderLayout());

用户提交昵称界面=new InputNameTextField(listTable);

int h=用户提交昵称界面getSize()height;

用户聊天界面=new ChatArea("",listTable,width,height-(h+5));

用户聊天界面setVisible(false);

提示条=new Label("正在连接到服务器,请稍等",LabelCENTER);

提示条setForeground(Colorred);

north=new Panel(new FlowLayout(FlowLayoutLEFT));

center=new Panel();

northadd(用户提交昵称界面);

northadd(提示条);

centeradd(用户聊天界面);

add(north,BorderLayoutNORTH);

add(center,BorderLayoutCENTER);

validate();

}

public void start()

{

if(socket!=null&&in!=null&&out!=null)

{ try

{

socketclose();

inclose();

outclose();

用户聊天界面setVisible(false);

}

catch(Exception ee)

{

}

}

try

{

socket = new Socket(thisgetCodeBase()getHost(), 6666);

in=new DataInputStream(socketgetInputStream());

out=new DataOutputStream(socketgetOutputStream());

}

catch (IOException ee)

{

提示条setText("连接失败");

}

if(socket!=null)

{

InetAddress address=socketgetInetAddress();

提示条setText("连接:"+address+"成功");

用户提交昵称界面setSocketConnection(socket,in,out);

northvalidate();

}

if(thread==null)

{

thread=new Thread(this);

threadstart();

}

}

public void stop()

{

try

{

socketclose();

thread=null;

}

catch(IOException e)

{

thisshowStatus(etoString());

}

}

public void run()

{

while(thread!=null)

{

if(用户提交昵称界面get能否聊天()==true)

{

用户聊天界面setVisible(true);

用户聊天界面setName(用户提交昵称界面getName());

用户聊天界面setSocketConnection(socket,in,out);

提示条setText("祝聊天愉快!");

centervalidate();

break;

}

try

{

Threadsleep(100);

}

catch(Exception e)

{

}

}

}

}

InputNameTextField。java

import javaawt;

import javanet;

import javaawtevent;

import javaio;

import javautilHashtable;

public class InputNameTextField extends Panel implements ActionListener,Runnable

{

TextField nameFile=null;

String name=null;

Checkbox male=null,female=null;

CheckboxGroup group=null;

Button 进入聊天室=null,退出聊天室=null;

Socket socket=null;

DataInputStream in=null;

DataOutputStream out=null;

Thread thread=null;

boolean 能否聊天=false;

Hashtable listTable;

public InputNameTextField(Hashtable listTable)

{

thislistTable=listTable;

nameFile=new TextField(10);

group=new CheckboxGroup();

male=new Checkbox("男",true,group);

female=new Checkbox("女",false,group);

进入聊天室=new Button("进入");

退出聊天室=new Button("退出");

进入聊天室addActionListener(this);

退出聊天室addActionListener(this);

thread=new Thread(this);

add(new Label("昵称:"));

add(nameFile);

add(male);

add(female);

add(进入聊天室);

add(退出聊天室);

退出聊天室setEnabled(false);

}

public void set能否聊天(boolean b)

{

能否聊天=b;

}

public boolean get能否聊天()

{

return 能否聊天;

}

public String getName()

{

return name;

}

public void setName(String s)

{

name=s;

}

public void setSocketConnection(Socket socket,DataInputStream in,DataOutputStream out)

{

thissocket=socket;

thisin=in;

thisout=out;

try{

threadstart();

}

catch(Exception e)

{

nameFilesetText(""+e);

}

}

public Socket getSocket()

{

return socket;

}

public void actionPerformed(ActionEvent e)

{

if(egetSource()==进入聊天室)

{

退出聊天室setEnabled(true);

if(能否聊天==true)

{

nameFilesetText("您正在聊天:"+name);

}

else

{

thissetName(nameFilegetText());

String sex=groupgetSelectedCheckbox()getLabel();

if(socket!=null&&name!=null)

{

try{

outwriteUTF("姓名:"+name+"性别:"+sex);

}

catch(IOException ee)

{

nameFilesetText("没有连通服务器"+ee);

}

}

}

}

if(egetSource()==退出聊天室)

{

try

{

outwriteUTF("用户离开:");

}

catch(IOException ee)

{

}

}

}

public void run()

{

String message=null;

while(true)

{

if(in!=null)

{

try

{

message=inreadUTF();

}

catch(IOException e)

{

nameFilesetText("和服务器断开"+e);

}

}

if(messagestartsWith("可以聊天:"))

{

能否聊天=true;

break;

}

else if(messagestartsWith("聊天者:"))

{

String people=messagesubstring(messageindexOf(":")+1);

listTableput(people,people);

}

else if(messagestartsWith("不可以聊天:"))

{

能否聊天=false;

nameFilesetText("该昵称已被占用");

}

}

}

}

以上就是关于java开发聊天功能用什么技术实现的全部的内容,包括:java开发聊天功能用什么技术实现的、这个JAVA程序(一个简单的网络聊天编程)空指针异常怎么处理...还有怎么向自己的IP写数据没反应..、如何用java实现一个简单网络通信过程等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

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

原文地址: http://outofmemory.cn/zz/10111306.html

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

发表评论

登录后才能评论

评论列表(0条)

保存