只能在同一區域網路上,該例子是在本機上實現。採用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(""); }}}