java网页聊天工具代码 java编写网络聊天程序( 七 )


JFrame f=new JFrame("BB");
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JTextArea ta=new JTextArea(12,30);//文本域java网页聊天工具代码,第一个参数为行数java网页聊天工具代码,第二个参数为列数
ta.setEditable(false);//文本域只读
JScrollPane sp=new JScrollPane(ta);//滚动窗格
JTextField tf=new JTextField(20);
JButton b=new JButton("发送");
p1.add(sp);
p2.add(tf);
p2.add(b);
f.add(p1,"Center");
f.add(p2,"South");
f.setBounds(300,300,360,300);
f.setVisible(true);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ServerSocket server=null;
Socket socket=null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try{
server=new ServerSocket(5000);
//ta.append("等待AA连接...\n");
socket=server.accept();
//ta.append("AA已连接\n");
bis=new BufferedInputStream(socket.getInputStream());
bos=new BufferedOutputStream(socket.getOutputStream());
MyThread1 mt=new MyThread1(bis,ta);
mt.start();
}catch(Exception e){
e.printStackTrace();
}
b.addActionListener(new ButtonActionListener1(tf,ta,bos));
}
}
class ButtonActionListener1 implements ActionListener{
JTextField tf;
JTextArea ta;
BufferedOutputStream bos;
public ButtonActionListener1(JTextField tf,JTextArea ta,BufferedOutputStream bos){
this.tf=tf;
this.ta=ta;
this.bos=bos;
}
public void actionPerformed(ActionEvent e){
String message=tf.getText();//获取文本框中java网页聊天工具代码的内容
if(!message.equals("")){
tf.setText("");//清空文本框
ta.append("BB:"+message+"\n");//添加到文本域并换行
try{
bos.write(message.getBytes());
bos.flush();
}catch(Exception ex){
System.out.println("发送失败java网页聊天工具代码!");
}
}
}
}
class MyThread1 extends Thread{
BufferedInputStream bis;
JTextArea ta;
public MyThread1(BufferedInputStream bis,JTextArea ta){
this.bis=bis;
this.ta=ta;
}
public void run(){
try{
while(true){
byte[] b=new byte[100];
int length=bis.read(b);
String message=new String(b,0,length);
ta.append("AA:"+message+"\n");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
求java网络聊天室(B/S模式)程序代码共四个java文件 , 源代码如下:
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import java.io.*;
import java.util.Hashtable;
public class ChatArea extends Panel implements ActionListener,Runnable
{
Socketsocket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread threadMessage=null;
TextArea 谈话显示区,私聊显示区=null;
TextField 送出信息=null;
Button 确定,刷新谈话区,刷新私聊区;
Label提示条=null;
String name=null;
Hashtable listTable;
ListlistComponent=null;
Choice privateChatList;
int width,height;
public ChatArea(String name,Hashtable listTable,int width,int height)
{
setLayout(null);
setBackground(Color.orange);
this.width=width;
this.height=height;
setSize(width,height);
this.listTable=listTable;
this.name=name;
threadMessage=new Thread(this);
谈话显示区=new TextArea(10,10);
私聊显示区=new TextArea(10,10);
确定=new Button("送出信息到:");
刷新谈话区=new Button("刷新谈话区");
刷新私聊区=new Button("刷新私聊区");
提示条=new Label("双击聊天者可私聊",Label.CENTER);
送出信息=new TextField(28);

推荐阅读