lz 你好
具体代码如下:
import javaawt;import javaawtevent;
import javaxswing;
public class Chat extends JFrame{
private JLabel enter,start;
private JTextField input;
private JTextArea output;
public Chat() {
super("小程序查看器:Clientclass");
enter = new JLabel("<html>小程序<br>Enter Text</html>");
entersetFont(new Font("宋体", FontPLAIN, 12));
start = new JLabel("小程序已启动。");
startsetFont(new Font("宋体", FontPLAIN, 12));
input = new JTextField(30);
output = new JTextArea(10,35);
outputsetEditable(false);
inputaddKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(egetKeyCode() == 10){
outputappend(inputgetText() + "\n");
}
}
});
setLayout(new FlowLayout(FlowLayoutLEFT,1,1));
getContentPane()add(enter);
getContentPane()add(input);
getContentPane()add(output);
getContentPane()add(start);
setLocation(300,200);
setSize(450,270);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(3);
}
public static void main(String[] args) {
new Chat();
}
}
希望能帮助你哈
给你一个简单的实现吧,注意一定要先运行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();
}
}
客户端:
package chatroom;
import javaawt;
import javaawtevent;
import javanet;
import javaio;
import javaxswing;
public class client extends JFrame implements ActionListener,Runnable{
JPanel conn,text,send;
JLabel name,sendto;
JComboBox list;
JButton con,snd,clear;
JTextArea talk;
JTextField who,say;
JScrollPane jsp;
Socket client;
InputStream is;
OutputStream os;
PrintStream ps;
BufferedReader br;
String receive,yousay;
Thread th;
DataInputStream dis;
Double tof;
client()
{
super("聊天室客户端");
thissetSize(800,600);
thissetResizable(false);
conn=new JPanel();
text=new JPanel();
send=new JPanel();
thisgetContentPane()add(conn);
connsetBounds(0, 0, thisgetWidth(),50);
name=new JLabel("姓名:");
who=new JTextField();
con=new JButton("连接");
connsetLayout(null);
connadd(name);
namesetBounds(30, 10, 50, 25);
connadd(who);
whosetBounds(80, 10, 150, 25);
connadd(con);
consetBounds(250,10, 60, 25);
thisgetContentPane()add(text);
textsetBounds(0,50,thisgetWidth(),450);
textsetLayout(new BorderLayout());
jsp=new JScrollPane();
talk=new JTextArea();
jspgetViewport()setView(talk);
textadd(jsp,"Center");
talksetLineWrap(true);
thisgetContentPane()add(send);
sendsetLayout(null);
sendsetBounds(0, 480, thisgetWidth(), 150);
sendto=new JLabel("发送到:");
snd=new JButton("发送");
list=new JComboBox();
say=new JTextField();
clear=new JButton("清空");
sendadd(sendto);
sendtosetBounds(30, 525, 50, 25);
sendadd(list);
listsetBounds(100, 525, 75, 25);
sendadd(say);
saysetEditable(true);
saysetBounds(200, 525, 300, 25);
sendadd(snd);
sndsetBounds(520, 525, 100, 25);
sendadd(clear);
clearsetBounds(650, 525, 100, 25);
thissetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);
thissetVisible(true);
conaddActionListener(this);
sndaddActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (aegetActionCommand()equals("连接"))
{
try
{
client=new Socket(InetAddressgetLocalHost(),55555);
talkappend("连接成功\n");
consetText("断开");
is=clientgetInputStream();
os=clientgetOutputStream();
th=new Thread(this);
String id=whogetText();
byte b[]=idgetBytes();
DataOutputStream dos=new DataOutputStream(os);
int len=blength;
doswriteInt(len);
doswrite(b);
thstart();
}catch(Exception e){talkappend("连接失败\n"+etoString()+"0000");}
}
else if(aegetSource()==snd)
{
if(listgetSelectedItem()toString()=="所有人")
{
yousay="@open"+saygetText();
byte b[]=yousaygetBytes();
DataOutputStream dos=new DataOutputStream(os);
try{
int len=blength;
doswriteInt(len);
doswrite(b);
}catch(Exception e)
{
Systemoutprint(etoString()+"1111");
}
}
else
{
yousay="@whisper"+saygetText();
byte b[]=yousaygetBytes();
byte w[]=listgetSelectedItem()toString()getBytes();
DataOutputStream dos=new DataOutputStream(os);
try{
int len=blength;
int wlen=wlength;
doswriteInt(len); //内容
doswrite(b);
doswriteInt(wlen); //发送对象
doswrite(w);
}catch(Exception e)
{
Systemoutprint(etoString()+"AAAA");
}
}
}
else if(aegetActionCommand()equals("断开"))
{
try
{
clientclose();
talkappend("连接已断开\n");
consetText("连接");
}catch(Exception e){Systemoutprintln(etoString()+"2222");}
}
}
public void run()
{
while(true)
{
try
{
dis=new DataInputStream(is);
tof=disreadDouble();
if(tof==11)
{
dis=new DataInputStream(is);
int number;
listremoveAllItems();
listaddItem("所有人");
number=disreadInt();
for(int i=0;i<number;i++)
{
int len=disreadInt();
byte b[]=new byte[len];
disread(b);
String name=new String(b);
listaddItem(name);
}
}
else if(tof==22)
{
try
{
dis=new DataInputStream(is);
int len=disreadInt();
byte b[]=new byte[len];
disread(b);
receive=new String(b);
talkappend(receive+"\n");
}catch(Exception e){JOptionPaneshowMessageDialog(this, "连接已断开","消息",JOptionPaneINFORMATION_MESSAGE);break;}
}
}catch(Exception e){JOptionPaneshowMessageDialog(this, "连接已断开","消息",JOptionPaneINFORMATION_MESSAGE);break;}
}
}
public static void main(String[] args) {
client cl=new client();
}
}
服务端:
package chatroom;
import javaawt;
import javaxswing;
import javanet;
import javautilVector;
import javaio;
public class server extends JFrame implements Runnable{
JPanel jp1;
JTextArea jta;
JScrollPane jsp;
Socket socket=null;
ServerSocket server;
InputStream is;
OutputStream os;
static int i=0,login;
int no;
static String s="";
Thread sr;
Thread th[]=new Thread[20];
static Vector ol=new Vector();
static public byte w[]=null;
static String from=""; //人名
static String to="";
static String fromtext=""; //内容
static String totext="";
server()
{
super("聊天室服务端");
thisgetContentPane()setLayout(new GridLayout(1,1));
thissetSize(400,300);
jp1=new JPanel();
jta=new JTextArea();
jsp=new JScrollPane();
thisgetContentPane()add(jp1);
jp1setLayout(new GridLayout(1,1));
jspgetViewport()setView(jta);
jp1add(jsp);
thissetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
server sr=new server();
srsr=new Thread(sr);
srsrstart();
sendtoall sta=new sendtoall();
returnfrom rf=new returnfrom(sr);
returnto rt=new returnto(sr);
stastart();
rfstart();
rtstart();
}
public void run()
{
try
{
server=new ServerSocket(55555);
while(true)
{
socket=serveraccept();
is=socketgetInputStream();
DataInputStream dis=new DataInputStream(is);
int len=disreadInt();
byte b[]=new byte[len];
disread(b);
String id=new String(b);
record v=new record(id,socket);
oladdElement(v);
for (int i=0;i<olsize();i++)
{
if (olelementAt(i)equals(v))
{
no=i;
}
}
login=1;
s=id+"已来到聊天室!";
th[no]=new Thread(new receive(this,no));
th[no]start();
}
}catch(Exception e){Systemoutprintln(etoString()+"aaaa");}
}
}
class receive implements Runnable
{
InputStream is;
OutputStream os;
server sr;
Socket sk;
int i;
String name;
String ip;
receive(server sr,int i)
{
thissr=sr;
thisi=i;
sk=((record)srolelementAt(i))ip;
name=((record)srolelementAt(i))name;
ip=((record)srolelementAt(i))ipgetInetAddress()toString();
}
public void run()
{
while(true)
{
try
{
is=skgetInputStream();
DataInputStream dis=new DataInputStream(is);
int len=disreadInt();
byte b[]=new byte[len];
disread(b);
String abc=new String(b);
srjtaappend(abc);
if(abcsubstring(0,5)equals("@open"))
{
servers=name+"["+ipsubstring(1, iplength())+"]"+"说:"+abcsubstring(5,abclength());
srjtaappend(servers+"\n");
}
else if(abcsubstring(0,8)equals("@whisper"))
{
int wlen=disreadInt();
srw=new byte[wlen];
disread(srw);
serverto=new String(srw);
serverfrom=((record)srolelementAt(i))name;
String ip=((record)srolelementAt(i))ipgetInetAddress()toString();
// servers=serverfrom+"对"+serverto+"["+ipsubstring(1, iplength())+"]"+"悄悄地说:"+abcsubstring(8,abclength());
serverfromtext="你对"+serverto+"["+ipsubstring(1, iplength())+"]"+"悄悄地说:"+abcsubstring(8,abclength());
servertotext=serverfrom+"["+ipsubstring(1, iplength())+"]"+"对你悄悄地说:"+abcsubstring(8,abclength());
srjtaappend(servers+"\n");
}
}catch(Exception e)
{
try
{
DataOutputStream dos=new DataOutputStream(os);
serverolremoveElementAt(i);
servers=name+"已离开聊天室";
serverlogin=1;
break;
}catch(Exception f){}
}
}
}
}
class sendtoall extends Thread
{
int len,number;
byte b[];
server sr;
Socket st;
OutputStream os;
DataOutputStream dos;
public void run()
{
while(true)
{
try
{
if(serverlogin==1)
{
number=0;
number=serverolsize();
dos=new DataOutputStream(os);
for(int i=0;i<serverolsize();i++)
{
st=((record)srolelementAt(i))ip;
os=stgetOutputStream();
dos=new DataOutputStream(os);
doswriteDouble(11);
doswriteInt(number);
for (int j=0;j<number;j++)
{
String name=((record)srolelementAt(j))name;
byte b[]=namegetBytes();
int len=blength;
doswriteInt(len);
doswrite(b);
}
}
serverlogin=0;
}
else if(!serversequals("")&&srolsize()>0)
{
b=serversgetBytes(); //String类型中 汉字占一个字节,但是byte类型中,汉字占两个字节
len=blength;
//len=serverslength();
//b=new byte[len];
//b=serversgetBytes();
for(int i=0;i<serverolsize();i++)
{
st=((record)srolelementAt(i))ip;
os=stgetOutputStream();
DataOutputStream dos=new DataOutputStream(os);
doswriteDouble(22);
doswriteInt(len);
doswrite(b);
}
servers="";
}
}catch(Exception e){Systemoutprintln(etoString()+"sdasd");}
}
}
}
class returnfrom extends Thread
{
int len,wlen;
byte b[];
byte w[];
server sr;
Socket st;
OutputStream os;
DataOutputStream dos;
//String from="",to="";
returnfrom(server sr)
{
thissr=sr;
}
public void run()
{
while(true)
{
if(!serverfromtextequals(""))
{
b=serverfromtextgetBytes();
len=blength;
srjtaappend(srfromtext);
try
{
for(int i=0;i<serverolsize();i++)
{
if(((record)srolelementAt(i))nameequals(serverfrom))
{
st=((record)srolelementAt(i))ip;
os=stgetOutputStream();
DataOutputStream dos=new DataOutputStream(os);
doswriteDouble(22);
doswriteInt(len);
doswrite(b);
}
}
}catch(Exception e){Systemoutprintln(etoString()+">
package comkumimhrservertest;
import javanet;
import javanio;
import javaniochannels;
import javaniocharset;
import javaawt;
import javaawtevent;
public class ChatClient {
private SocketChannel sc = null;
private String name = null;
private Frame f;
private TextArea ta;
private TextField tf;
private boolean runnable = true;
public static void main(String[] args){
ChatClient cc = new ChatClient();
cccreateUI();
ccinputName();
ccconnect();
new ReceiveThread(cc,ccgetTextArea())start();
}
public SocketChannel getSc(){
return sc;
}
public void setName(String name){
thisname = name;
}
public TextArea getTextArea(){
return ta;
}
public TextField getTextField(){
return tf;
}
public boolean getRunnable(){
return runnable;
}
public void stop(){
runnable = false;
}
public void shutDown(){
try{
scwrite(ByteBufferwrap("bye"getBytes("UTF-8")));
taappend("Exit in 5 seconds!");
thisstop();
Threadsleep(5000);
scclose();
}catch(Exception e){
eprintStackTrace();
}
Systemexit(0);
}
public void createUI(){
f = new Frame("Client");
ta = new TextArea();
tasetEditable(false);
tf = new TextField();
Button send = new Button("Send");
Panel p = new Panel();
psetLayout(new BorderLayout());
padd(tf,"Center");
padd(send,"East");
fadd(ta,"Center");
fadd(p,"South");
MyClientListener listener = new MyClientListener(this);
sendaddActionListener(listener);
tfaddActionListener(listener);
faddWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
ChatClientthisshutDown();
}
});
fsetSize(400,400);
fsetLocation(600,0);
fsetVisible(true);
tfrequestFocus();
}
public boolean connect(){
try{
sc = SocketChannelopen();
//"zlg"为目标计算机名
InetSocketAddress isa = new InetSocketAddress("192168143",8814);
scconnect(isa);
scconfigureBlocking(false);
scwrite(ByteBufferwrap(namegetBytes("UTF-8")));
}catch(Exception e){
eprintStackTrace();
}
return true;
}
public void inputName(){
String name = javaxswingJOptionPaneshowInputDialog("Input Your Name:");
thissetName(name);
fsetTitle(name);
}
}
class MyClientListener implements ActionListener{
private ChatClient client;
public MyClientListener(ChatClient client){
thisclient = client;
}
public void actionPerformed(ActionEvent e){
TextField tf = clientgetTextField();
String info = tfgetText();
if(infoequals("bye")){
clientshutDown();
}else{
try{
clientgetSc()write(ByteBufferwrap(infogetBytes("UTF-8")));
}catch (Exception e1) {
e1printStackTrace();
}
}
tfsetText("");
tfrequestFocus();
}
}
class ReceiveThread extends Thread{
private ChatClient client;
private TextArea ta;
public ReceiveThread(ChatClient client,TextArea ta){
thisclient = client;
thista = ta;
}
public void run(){
SocketChannel sc = clientgetSc();
ByteBuffer byteBuffer = ByteBufferallocate(2048);
CharBuffer charBuffer = null;
Charset charset = CharsetforName("UTF-8");
CharsetDecoder decoder = charsetnewDecoder();
String msg = null;
int n = 0;
try{
while(clientgetRunnable()){
n = scread(byteBuffer);
if(n>0){
byteBufferflip();
charBuffer = decoderdecode(byteBuffer);
msg = charBuffertoString();
taappend(msg + "\n");
}
byteBufferclear();
Threadsleep(500);
}
}catch(Exception e){
eprintStackTrace();
Systemexit(0);
}
}
}
import javaio;
import javanio;
import javaniochannels;
import javaniocharset;
import javanet;
import javautil;
public class ICQServer {
private Selector selector = null;
private ServerSocketChannel ssc = null;
//服务器端通信端口号
private int port = 8814;
private Hashtable<String, SocketChannel> userList = null;
public ICQServer() {}
public ICQServer(int port) {
thisport = port;
}
//初始化服务器
public void init() {
try {
//创建选择器对象
selector = Selectoropen();
//创建ServerSocketChannel
ssc = ServerSocketChannelopen();
//设置ServerSocketChannel为非阻塞模式
sscconfigureBlocking(false);
InetAddress ip = InetAddressgetLocalHost();
Systemoutprintln("主机地址 --------> " + ip);
InetSocketAddress isa = new InetSocketAddress(ip, port);
//将与本通道相关的服务器套接字对象绑定到指定地址和端口
sscsocket()bind(isa);
//创建在线用户列表
userList = new Hashtable<String, SocketChannel> ();
}
catch (IOException e) {
Systemoutprintln("初始化服务器时异常,原因 --------> " + egetMessage());
}
}
//启动服务器
public void start() {
try {
//将ServerSocketChannel注册到Selector上,准备接收新连接请求
SelectionKey acceptKey = sscregister(selector, SelectionKeyOP_ACCEPT);
SocketChannel sc;
int n;
String name; //用户名
String msg; //用户发言信息
while (true) {
//选择当前所有处于就绪状态的通道所对应的选择键,并将这些键组成已选择键集
n = selectorselect(); //n为已选择键集中键的个数
if (n > 0) {
//获取此选择器的已选择键集。
Set readyKeys = selectorselectedKeys();
Iterator it = readyKeysiterator();
//遍历当前已选择键集
while (ithasNext()) {
SelectionKey key = (SelectionKey) itnext();
//从当前已选择键集中移除当前键,避免重复处理
itremove();
//如果当前键对应的通道已准备好接受新的套接字连接
if (keyisAcceptable()) {
//获取当前键对应的可选择通道(ServerSocketChannel)
ssc = (ServerSocketChannel) keychannel();
//接收新的套接字连接请求,返回新建的SocketChannel
sc = (SocketChannel) sscaccept();
//如果有新用户接入
if (sc != null) {
//接收新上线用户姓名
name = readMessage(sc);
//设置新建的SocketChannel为非阻塞模式
scconfigureBlocking(false);
//将新建的SocketChannel注册到Selector上,准备进行数据"写" *** 作,
//并将当前用户名以附件的方式附带记录到新建的选择键上。
SelectionKey newKey = scregister(selector,
SelectionKeyOP_WRITE, name);
//将新上线用户信息加入到在线用户列表
userListput(name, sc);
//发送"新用户上线"通知
transmitMessage(name + " in!", "--Server Info--");
}
}
//否则,如果当前键对应的通道已准备好进行"写" *** 作
else if (keyisWritable()) {
//获取当前键对应的可选择通道(SocketChannel)
sc = (SocketChannel) keychannel();
//接收该通道相应用户的发言信息
msg = readMessage(sc);
//获取选择键上附带记录的当前用户名
name = keyattachment()toString();
//如果用户提出要下线
if (msgequals("bye")) {
//从在线用户列表中移除当前用户
userListremove(name);
//注销当前选择键对应的注册关系
keycancel();
//关闭当前可选择通道
scclose();
//发送"用户下线"通知
transmitMessage(name + " out!", "--Server Info--");
}
//否则,如果接收到的用户发言信息非空("")
else if (msglength() > 0) {
//转发用户发言信息
transmitMessage(msg, name);
}
}
}
}
//延时循环,降低服务器端处理负荷
Threadsleep(500);
}
}
catch (Exception e) {
Systemoutprintln("启动服务器时异常,原因 --------> " + egetMessage());
}
}
//转发用户发言信息
public void transmitMessage(String msg, String name) {
try {
ByteBuffer buffer = ByteBufferwrap( (name + ":" + msg)getBytes("UTF-8"));
//将字节数组包装到缓冲区中
Collection channels = userListvalues();
SocketChannel sc;
for (Object o : channels) {
sc = (SocketChannel) o;
scwrite(buffer);
//将缓冲区数据写入聊天面板(TextArea)
bufferflip();
//将缓冲区ByteBuffer的极限值设置为当前数据实际大小,将缓冲区的值设置为0
}
}
catch (Exception e) {
Systemoutprintln("转发用户发言信息时异常,原因 --------> " + egetMessage());
}
}
//接收用户发言信息
public String readMessage(SocketChannel sc) {
String result = null;
int n = 0;
ByteBuffer buf = ByteBufferallocate(1024);
try {
n = scread(buf);
bufflip();
Charset charset = CharsetforName("UTF-8");
CharsetDecoder decoder = charsetnewDecoder();
CharBuffer charBuffer = decoderdecode(buf);
result = charBuffertoString();
}
catch (IOException e) {
Systemoutprintln("接收用户发言信息时异常,原因 --------> " + egetMessage());
}
return result;
}
public static void main(String args[]) {
ICQServer server = new ICQServer();
serverinit();
serverstart();
}
}
以上就是关于java的问题,一个简单的聊天程序全部的内容,包括:java的问题,一个简单的聊天程序、如何用java做一个聊天小程序 要求使用图形用户界面,可以实现一个聊天室中多人聊天,也可以两人私聊,、急需一个用java 语言写的聊天程序等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)