socket编程(java实现)
生活随笔
收集整理的這篇文章主要介紹了
socket编程(java实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
socket編程
socket,又稱套接字,是在不同的進程間進行網絡通訊的一種協議、約定或者說是規范。
對于socket編程,它更多的時候像是基于TCP/UDP等協議做的一層封裝或者說抽象,是一套系統所提供的用于進行網絡通信相關編程的接口。
socket編程基本流程
socket編程(java實現)
服務端使用ServerSocket綁定IP和端口,使用Accept監聽端口是否有客戶端發送連接請求,一旦有客戶端發送連接請求,
服務端就回送連接信息,正式建立連接。Server端和Client端都可以通過Send,Write等方法與對方通信。
服務器:
public class TcpSocketServer {public static void main(String[] args) {try {// 創建服務端socket 綁定端口ServerSocket serverSocket = new ServerSocket();//綁定ipserverSocket = new ServerSocket(8088, 10, InetAddress.getByName("192.168.0.110"));// 創建客戶端socket 用戶下面接收客戶端socket對象Socket socket = new Socket();System.out.println("等待客戶端連接...");//循環監聽等待客戶端的連接while(true){// 監聽客戶端 沒有接受到數據才會停在此處 接受到往下執行socket = serverSocket.accept();//發送內容實現線程的創建ServerThread thread = new ServerThread(socket); thread.start();//獲取客戶端的ipInetAddress address=socket.getInetAddress();System.out.println("當前鏈接的客戶端的IP:"+address.getHostAddress());}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();} }} public class ServerThread extends Thread{private Socket socket = null;public ServerThread(Socket socket) {this.socket = socket;}public void run() {InputStream is=null;InputStreamReader isr=null;BufferedReader br=null;OutputStream os=null;PrintWriter pw=null;try {is = socket.getInputStream();isr = new InputStreamReader(is);br = new BufferedReader(isr);String info = null;while((info=br.readLine())!=null){System.out.println("客戶端:"+info);}//非關閉連接 僅關閉一方的發送狀況socket.shutdownInput();os = socket.getOutputStream();pw = new PrintWriter(os);pw.write("服務器歡迎你1");pw.flush();} catch (Exception e) {// TODO: handle exception} finally{//關閉資源try {if(pw!=null)pw.close();if(os!=null)os.close();if(br!=null)br.close();if(isr!=null)isr.close();if(is!=null)is.close();if(socket!=null)socket.close();} catch (IOException e) {e.printStackTrace();}}} }客戶端:
public class TcpSocketClient {public static void client() throws InterruptedException {try {// 和服務器創建連接Socket socket = new Socket("192.168.0.111", 8088);// 要發送給服務器的信息OutputStream os = socket.getOutputStream();PrintWriter pw = new PrintWriter(os);pw.write("狀態已改變");//flush方法是用于將輸出流緩沖的數據全部寫到目的地。//所以一定要在關閉close之前進行flush處理,即使PrintWriter有自動的flush清空功能pw.flush();socket.shutdownOutput();// 從服務器接收的信息InputStream is = socket.getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(is));String info = null;while ((info = br.readLine()) != null) {System.out.println("我是客戶端,服務器返回信息:" + info);}br.close();is.close();os.close();pw.close();socket.close();} catch (Exception e) {e.printStackTrace();}} }代碼源自:https://blog.csdn.net/weixin_43784880/article/details/105963960
總結
以上是生活随笔為你收集整理的socket编程(java实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java中Map有哪些实现类
- 下一篇: java双层for循环