java socket通訊:聊天器(1)

目的:實現多個客戶之間的通訊

首先,這個聊天器的框架是這樣的:java

 

 對於服務器端:創建socket,鏈接到服務器,而且開始監聽。數組

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.net.*;
public class MultiTalkServer{
    static int clientnum = 0;
    //建立一個arraylist數組來保存socket,
    public static List <Socket> socketList = new ArrayList <Socket>();
    public static void main(String args[])throws IOException{
        ServerSocket serverSocket = null;
        boolean listening = true;
        try {
            serverSocket= new ServerSocket(4700);
            System.out.println("歡迎來到聊天室。");
        }catch(IOException e) {
            System.out.println("Could not listen on port:4700.");
            System.exit(-1);
        }
        while (listening) {
            clientnum++;
            Socket st = serverSocket.accept();//先建立一個socket
            //此處會阻塞,等待接收
            socketList.add(st);//將這個線程添加到list裏
            System.out.println("上線通知: 用戶" + clientnum+"上線啦!"); 
            new ServerThread(st,clientnum).start();//再建立一個服務端線程
        }
        serverSocket.close();
    }
}

服務器線程:緩存

import java.io.*;
import java.net.*;
public class ServerThread extends Thread{
    Socket socket = null;//服務器的套接字
    int clientnum;
    String line;
    //將line定義在外面
    public ServerThread(Socket socket,int num){
        this.socket=socket;
        clientnum=num+1;
    }
    public void run() {
        try {
            BufferedReader is = new BufferedReader(new
            InputStreamReader(socket.getInputStream()));//is:從緩存區讀入
            
            PrintWriter os = new PrintWriter(socket.getOutputStream());//os:從緩存區輸出
            
            BufferedReader sin = new BufferedReader(
                    new InputStreamReader(System.in));//系統標準輸入
            
            System.out.println("Client:"+clientnum+is.readLine());//顯示從客戶端讀入的對象,在這裏等待客戶端輸入
            
            line=sin.readLine();
            //前面是初始化
            while(!line.equals("bye")) {
                os.println(line);//向客戶端輸出該字符串
                os.flush();//刷新,讓客戶端接收到
                System.out.println("Server:"+line);//顯示服務端讀入的字符
                System.out.println("Client:"+clientnum+is.readLine());//再次從客戶端讀入字符串
                line=sin.readLine();//從服務端讀入字符
            }
            os.close();
            is.close();
            socket.close();
                    
        }catch(Exception e) {
            System.out.println("Error:"+e);
        }
    }
}

客戶端:服務器

import java.net.*;
import java.io.*;
public class TalkClient{

    public static void main(String args[]){
        try {
            Socket socket = new Socket("127.0.0.1",4700);
            System.out.print("已鏈接成功,");
            new Thread(new ClientThread(socket)).start();
            new Thread(new ClientThread2(socket)).start();
        }catch(Exception e) {
            System.out.println("Error"+e);
        }
        
}
}

客戶端線程1:框架

import java.io.*;
import java.net.*;
public class ClientThread extends Thread{
    Socket socket;
    String line;
    public ClientThread(Socket socket) {
        this.socket = socket;

    }
    public void run(){
        try {
            BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            while(true) {
                line = is.readLine();
                out.println(line); //向服務器輸入;
                out.flush();
            }
        }catch(Exception e){
            System.out.println("Error:"+e);
        }
    }
}

客戶端線程2:socket

import java.io.*;
import java.net.*;
public class ClientThread2 extends Thread{
    Socket socket;

    public ClientThread2(Socket socket) {
        this.socket = socket;
    }
    public void run(){
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while(true) {
                String line = in.readLine();
                System.out.println(line); 
            }
        }catch(Exception e){
            System.out.println("Error:"+e);
        }
    }
}

展現結果:this

相關文章
相關標籤/搜索