1. 程式人生 > >socket程式設計(一),實現伺服器與客戶端簡單通訊

socket程式設計(一),實現伺服器與客戶端簡單通訊

本節主講客戶端向服務傳送資訊,伺服器轉發給客戶端,當然也可以稍微改一下程式碼可以實現互傳訊息,不再贅述。
難點在於伺服器端的程式碼思路:
(1)主程式Socket socket=server.accept();等待客戶端連線。
(2)建立執行緒函式,實現連線成功後建立一個新的執行緒,伺服器轉發客戶端訊息。
TCPServer.java

package com.ysu.server.chatroom;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public
class TCPServer { private int port=4443;//預設伺服器埠 public void setPort(int port){ this.port=port; } public int getPort(){ return this.port; } public void servers(){ try { ServerSocket server=new ServerSocket(this.getPort()); int i=0
; while(true){ //等待客戶端連線 Socket socket=server.accept(); i++; System.out.println("第"+i+"個客戶端連線!"); //連線成功後建立一個新的執行緒實現伺服器通訊服務 new Thread(new ThreadServer(socket)).start(); } } catch
(IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) throws IOException { new TCPServer().servers(); } }

ThreadServer.java

package com.ysu.server.chatroom;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ThreadServer implements Runnable{
    private Socket socket;

    public ThreadServer(Socket socket){
        this.socket=socket;

    }
    public Socket getSocket(){
        return this.socket;
    }
    //多執行緒執行函式
    public void run() {
        BufferedReader in= null;
        PrintWriter write = null;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        try {
            //獲取輸出流
            write=new PrintWriter(this.socket.getOutputStream());
            //獲取輸入流
            in=new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            String str=in.readLine();

            while(!(str==null||str.equals("end")||str.equals(""))){             
            System.out.println(str);
            write.println("伺服器(轉)"+str);
            write.flush();//強制重新整理緩衝區,將緩衝區全部輸出
            str=in.readLine();
            }   

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                //關閉流
                write.close();
                in.close();
                this.getSocket().close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

以上是伺服器端的程式碼,下面是客戶端程式碼比伺服器簡單。
TCPClient1.java

package com.ysu.server.chatroom;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;


public class TCPClient1 {

    public static void main(String[] args) {
        try {
            Socket socket=new Socket("127.0.0.1",4443);
            System.out.println("客戶1:服務已經連線......");
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            PrintWriter write=new PrintWriter(socket.getOutputStream());
            BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));

            //System.out.println(in.readLine());
            String line=br.readLine();
            //System.out.println(line);
            while(!line.equals("end")){
                //System.out.println(line);
                write.println("客戶端1:"+line);
                write.flush();
                System.out.println(in.readLine());
                line=br.readLine();
            }
            write.close();
            in.close();
            br.close();
            socket.close();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

執行效果圖:
這裡寫圖片描述