???1)建立一個服務器ServerSocket,并同時定義好ServerSocket的監聽端口;
???2)ServerSocket 調用accept()方法,使之處于阻塞。
???3)創建一個客戶機Socket,并設置好服務器的IP和端口。
???4)客戶機發出連接請求,建立連接。
???5)分別取得服務器和客戶端ServerSocket 和Socket的InputStream和OutputStream.
???6)? 利用Socket和ServerSocket進行數據通信。
?
服務器:
import java.net.*;
import java.io.*;
public class MypwServer {
?public MypwServer() {
??super();
??// TODO Auto-generated constructor stub
?}
??? public void Activate() throws Exception{
???
??? ??ServerSocket ss = new ServerSocket(5678);
??? ?
??? ??Socket soc = ss.accept();
??? ??
??? ?BufferedReader br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
??? ?PrintWriter pw = new PrintWriter(soc.getOutputStream());
??? ?while(true){
??? ??String str = br.readLine();
??? ??pw.println(str);
??? ??//pw.flush();
//??? ??if(str.equals("end")){
//??? ???break;
//??? ??}
?? ?//?System.out.println(str);
??? ?}
???
??? }
???
??? public static void main(String[] args){
??? ?MypwServer mys = new MypwServer();
??? ?try {
???mys.Activate();
??} catch (Exception e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
??}
??? ?
??? }
}
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Client extends JFrame implements ActionListener
{
?
?static String str;
?static String sy;
?static PrintStream p;
?JButton btn,btn1;
?JLabel ble;
?static JTextArea tex? = new JTextArea();
?static JTextArea tex1 = new JTextArea();
?public Client()
?{
??this.setTitle("聊天室");
??this.setSize(500,420);
??this.setLocation(230,60);
??this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
??this.setResizable(false);
??this.setLayout(null);
??
??Container con = this.getContentPane();
??btn? = new JButton("發送");
??btn1 = new JButton("關閉");
??btn.addActionListener(this);
??btn1.addActionListener(this);
??btn.setBounds(20,360,60,20);
??btn1.setBounds(120,360,60,20);
??tex.setBounds(0,0,250,150);
??tex1.setBounds(0,180,250,160);
??con.add(btn);
??con.add(btn1);
??con.add(tex);
??con.add(tex1);
??
??this.setVisible(true);
?}
?
?
?客戶機:
?public static void main(String[] args) throws Exception
?{
??new Client();
??Socket so = new Socket("localhost",5678);
??BufferedReader br = new BufferedReader(new InputStreamReader(so.getInputStream()));
??
??p = new PrintStream(so.getOutputStream());
??BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
??
??while(true)
??{
???
???str = tex1.getText();
???
???if (str.equals(null))
????break;
??}
??so.close();
?}
?
?
?public void actionPerformed(ActionEvent a)
?{
??Object obj = a.getSource();
??
??if(obj == btn)
??{
???p.println(str);
???tex.append(str + "\n");
???tex1.setText("");
??}
??
??if(obj == btn1)
??{
???System.exit(0);
??}
?}
}