首頁 > Java > java教程 > 主體

Java中socket程式設計的實作過程(程式碼實例)

不言
發布: 2018-09-25 15:07:46
原創
8087 人瀏覽過

這篇文章帶給大家的內容是關於socket程式的實現過程,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

1.socket 伺服器建構

實例化socket伺服器,循環取得請求

package com.orange.util;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
 * socket服务器
 * 
 * @author Chengjq
 *
 */
public class SocketServer {
    public static int count = 0;
    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        int port = 4404;
        // 首先直接创建serversocket
        ServerSocket serverSocket = null;
        Socket socket = null;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("启动socketServer成功,等待客户端的连接");
            while (true) {
                socket = serverSocket.accept();
                System.out.println("有新的客户端请求连接");
                SocketThread st = new SocketThread(socket);
                st.start();
                ChatManager.getChatManager().add(st);
                //启动定时任务,如果10s内没有进程
                /*Runnable runnable = new Runnable() {
                    int clientNum = 0;
                    public void run() {  
                        // task to run goes here  
                        clientNum = ChatManager.getChatManager().vector.size();
                        System.out.println("剩余客户端数量:"+clientNum);
                        if(clientNum ==0 ){
                            System.out.println("连接超时,或者无客户端连接,关闭serverSocket");
                            //关闭socket
                            //.....
                        }
                    }  
                };  
                ScheduledExecutorService service = Executors  
                        .newSingleThreadScheduledExecutor();  
                // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间  
                service.scheduleAtFixedRate(runnable, 2, 10, TimeUnit.SECONDS);  */
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            System.out.println("serverSocket已超时");
            try {
                socket.close();
                serverSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
}
登入後複製

SocketThread類別實作多執行緒通訊

package com.orange.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * SocketThread实现多线程通信
 * 
 * @author Administrator
 *
 */
public class SocketThread extends Thread {
	ServerSocket serverSocket = null;
	Socket socket = null;
	public SocketThread(ServerSocket serverSocket,Socket socket) {
		super();
		this.serverSocket = serverSocket;
		this.socket = socket;
	}
	public SocketThread(Socket socket) {
		super();
		this.socket = socket;
	}
	public void out(String out) {
        try {
            socket.getOutputStream().write(out.getBytes("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	public void publish(String out){
		ChatManager.getChatManager().publish(this, out);
	}
	

	@Override
	public void run() {
		// TODO Auto-generated method stub
		BufferedReader socketIn = null;
		PrintWriter socketOut = null;
		String inMess = null;
		try {
			socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			socketOut = new PrintWriter(socket.getOutputStream());
			while (true) {
				inMess = socketIn.readLine();
				publish(inMess);
				if("bye".equals(inMess)){
					ChatManager.getChatManager().remove(this);
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				System.out.println("已结束当前会话");
				socketOut.close();
				socketIn.close();
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}
登入後複製

單例Chatmanage,對所有客戶端執行緒管控處理

package com.orange.util;
import java.util.Vector;
public class ChatManager {
    // 实现单例化
    private ChatManager() {
    };
    private static final ChatManager cm = new ChatManager();
    public static ChatManager getChatManager() {// 返回值为ChatManager
        return cm;
    }
    // 单例化完成
    Vector<SocketThread> vector = new Vector<SocketThread>();

    public void add(SocketThread st) {// 为当前集合添加SocketThread对象
        vector.add(st);
    }
    
    public void remove(SocketThread st) {// 当前客户端关闭连接
        vector.remove(st);
    }
    
    public void removeall() {// 关闭所有连接
        for (int i = 0; i < vector.size(); i++) {// 遍历所有的线程
            SocketThread csChatSocket = vector.get(i);
            if(csChatSocket!=null){
                vector.remove(csChatSocket);
            }
                
        }
    }

    // 某一个线程向其他的客户端发送信息
    public void publish(SocketThread st, String out) {
        for (int i = 0; i < vector.size(); i++) {// 遍历所有的线程
            SocketThread csChatSocket = vector.get(i);
            if (csChatSocket != st)// 判断不是当前线程就发送此消息
                csChatSocket.out(out + "\n");
        }
    }

    // 向当前线程发信息
    public void publish_present(SocketThread st, String out) {
        st.out(out + "\n");
    }
}
登入後複製

至此,伺服器建置完成

2.客戶端(建立兩個客戶端)

客戶端1(監聽指定伺服器,透過控制台輸入訊息進行伺服器與客戶端以及客戶端之間的通信,)

package com.orange;

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

/**
 * 客户端1
 * @author Chengjq
 *
 */
public class SocketClient1 {

	@SuppressWarnings("static-access")
	public static void main(String[] args) {
		try {
			//初始化客户端
			Socket socket = new Socket("127.0.0.1", 4404);
			BufferedReader readline = new BufferedReader(new InputStreamReader(System.in));
			//获取输出打印流
			PrintWriter socketOut = new PrintWriter(socket.getOutputStream());
			String outTemp = null;
			System.out.println("开始准备向服务器端发起请求---\n自己:");
			// 已启动连接socket服务器,准备实时接收来自其他客户端的消息
			GetMess getMess = new GetMess(socket);
			getMess.start();
			// 通过控制台发送消息给其他客户端,以“bye”为结束语
			while ((outTemp = readline.readLine()) != null) {
				//发送信息
				socketOut.println(outTemp);
				socketOut.flush();
				if("bye".equals(outTemp)){
					break;
				}
			}
			getMess.currentThread().interrupt();
			//依次关闭各种流
			readline.close();
			socketOut.close();
			socket.close();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
登入後複製

客戶端2

package com.orange;

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 SocketClient2 {
    @SuppressWarnings("static-access")
    public static void main(String[] args) {
        
        try {
            //初始化客户端
            Socket socket = new Socket("127.0.0.1", 4404);
            BufferedReader readline = new BufferedReader(new InputStreamReader(System.in));
            //获取输出打印流
            PrintWriter socketOut = new PrintWriter(socket.getOutputStream());
            String outTemp = null;
            System.out.println("开始准备向服务器端发起请求---\n自己:");
            // 已启动连接socket服务器,准备实时接收来自其他客户端的消息
            GetMess getMess = new GetMess(socket);
            getMess.start();
            // 通过控制台发送消息给其他客户端,以“bye”为结束语
            while ((outTemp = readline.readLine()) != null) {
                //发送信息
                socketOut.println(outTemp);
                socketOut.flush();
                if("bye".equals(outTemp)){
                    break;
                }
            }
            getMess.currentThread().interrupt();
            //依次关闭各种流
            readline.close();
            socketOut.close();
            socket.close();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        
    }
}
登入後複製

GetMess(多執行緒處理獲取其他客戶端的訊息並且展示)

package com.orange;

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

public class GetMess extends Thread {

    Socket socket = null;
    
    public GetMess(Socket socket) {
        super();
        this.socket = socket;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        BufferedReader socketIn = null;
        try {
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            socketIn = new BufferedReader(isr);
            String inTemp = null;
            while(true){
                inTemp = socketIn.readLine();
                if(inTemp != null && !"bye".equals(inTemp) ){
                    System.out.println("好友:\n"+inTemp);
                }else{
                    System.out.println("好友:\n已下线,关闭当前回话");
                    break;
                } 
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                Thread.currentThread().interrupt();
                socketIn.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        
    }

    
    
    
}
登入後複製

ok,簡單的sockte服務與客戶端完成了

先啟動server

在分別啟動client

##輸入結束bye,關閉目前會話

以上是Java中socket程式設計的實作過程(程式碼實例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板