只能在同一局域网上,该例子是在本机上实现。采用TCP通信协议。
客户端程序:
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class MyClient3 extends JFrame implements ActionListener
{
JTextArea jta=null;//定义一个文本域显示聊天类容
JTextField jtf=null;//顶一个文本框用来显示从键盘输入的内容
JButton jb=null;//发送按钮控制
JPanel jp=null;//定义一个面板,放置文本域
JScrollPane jsp=null;//滑动面板
PrintWriter out=null;//在socket中定义输出流
public MyClient3(){
//初始化聊天界面
jta=new JTextArea();
//初始化滑动面板,并且将文本域放在滑动面板中
jsp=new JScrollPane(jta);
jtf=new JTextField(20);
jb=new JButton("发送");
jb.addActionListener(this);
jp=new JPanel();
jp.add(jtf);
jp.add(jb);
this.add(jsp,"Center");//JFrame和JDialog默认就是边界布局
this.add(jp,"South");
this.setTitle("QQ简易聊天 客户端");
this.setSize(400,300);
this.setVisible(true);
try{
//TCP通信的客户端通过套接字建立连接
Socket s=new Socket("169.254.74.22",9988);
//定义一个缓冲区从socket中的读取流
BufferedReader brin=new BufferedReader
(new InputStreamReader(s.getInputStream()));
//发送消息的写出流
out=new PrintWriter(s.getOutputStream(),true);
while(true)
{
//显示从服务端读取的信息
String info=brin.readLine();
jta.append("服务器对客户端说:"+info+"\r\n");
}
}catch(Exception e){
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent arg0){
if(arg0.getSource()==jb)
{
//客户端从文本框中读入的信息
String info=jtf.getText();
//jta.append(info);
//将文本框中的用户输入的信息显示在文本域中
jta. append("客户端对服务器说:"+info+"\r\n");
//将文本框中用户输入的信息发送到服务端
out.println(info);
//清空文本框,便于下次继续书写信息
jtf.setText("");
}
}
public static void main(String[] args)
{
new MyClient3();
}
}
服务器端程序:
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.awt.event.*;
public class MyServer3 extends JFrame implements ActionListener
{
JTextArea jta=null;
JTextField jtf=null;
JButton jb=null;
JPanel jp=null;
JScrollPane jsp=null;
PrintWriter out=null;
public static void main(String[] args)
{
new MyServer3();
}
public MyServer3(){
jta=new JTextArea();
jsp=new JScrollPane(jta);
jtf=new JTextField(20);
jb=new JButton("发送");
jb.addActionListener(this);
jp=new JPanel();
jp.add(jtf);
jp.add(jb);
this.add(jsp,"Center");
this.add(jp,"South");
this.setTitle("QQ简易聊天 服务端");
this.setSize(400,300);
this.setVisible(true);
try{
//创建服务器端服务,监听9988端口
ServerSocket ss=new ServerSocket(9988);
//获取客户端的连接对象,服务端要指定是哪个客户端的连接
Socket s=ss.accept();
BufferedReader brin=new BufferedReader
(new InputStreamReader(s.getInputStream()));
out=new PrintWriter(s.getOutputStream(),true);
while(true)
{
String info=brin.readLine();
jta.append("客户端对服务端说:"+info+"\r\n");
}
}catch(Exception e){
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent arg0){
if(arg0.getSource()==jb)
{
String info=jtf.getText();
jta.append("服务器对客户端说:"+info+"\r\n");
//jta.setText(info);
out.println(info);
//jta.setText(info);
jtf.setText("");
}
}
}