談一談socket與java

來源:互聯網
上載者:User

標籤:而且   輸入資料流   方案   固定   catch   用戶端   cli   stack   server   

用java中socket實現socket聊天

1,      什麼是socket

Socket 是指網路通訊端,什麼是通訊端呢?    這是網路上一種端對端的網路通訊協定,連接埠就是進程號,socket在網路中讓這兩個端通訊形成連接埠直接通訊,所以socket的參數可想而知就是兩端ip和連接埠號碼了;

再說在網路中,總要有人付出,要在網路中等著別人連結,不然的話你一點想連別人,別人在兩點想連你,怎麼也不可能連上,總有喲個人需要做等待的角色,這個角色就是服務端也就是serverSocket,他在網路中提供一個固定的ip和連接埠號碼通訊端;

2,      在Java中實現socket介面

在Java中提供了兩個用來建立socket連結都在java.net包中,在用戶端要用Socket(addr,port)//參數是遠程服務的地址和連接埠號碼;另一個在服務端中用ServerSocket(port) 建立一個等待的socket端,同時使用serversocket.accept() 在服務端動態等待並接受一個前來請求連結的socket請求

一旦serversocket.accept()方法獲得一個連結,就會封裝出一個Socket物件服務端可用這個對象,獲得用戶端的資訊並向用戶端發送資訊;話不多說,上代碼;

  

package testpackage;/* * @author:mayeye * @about:服務端 * */import java.net.*;import java.io.*;public class TestServer {    public static void main(String[] args) {        //try {            System.out.println("=============================");            ServerSocket server=null;            try {                server=new ServerSocket(1233);            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            Socket client = null;            try {                client = server.accept();                System.out.println("ip為:"+client.getInetAddress()+"的用戶端連結了");                System.out.println("port為:"+client.getPort()+"的用戶端連結了");                System.out.println("Localport為:"+client.getLocalPort()+"的用戶端連結了");            } catch (IOException e1) {                // TODO Auto-generated catch block                e1.printStackTrace();            }            String line = null;            BufferedReader is = null;            try {                is = new BufferedReader(new InputStreamReader(client.getInputStream()));            } catch (IOException e1) {                // TODO Auto-generated catch block                e1.printStackTrace();            }            PrintWriter os = null;            try {                os = new PrintWriter(client.getOutputStream());            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));            try {                System.out.println("Client:"+is.readLine());            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            try {                line=sin.readLine();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }                        while(!line.equals("bye")){                os.println(line);                os.flush();                System.out.println("Server:"+line);                    try {                    System.out.println("Client:"+is.readLine());                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                try {                    line=sin.readLine();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }            os.close();            try {                is.close();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            try {                client.close();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            try {                server.close();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            System.out.println("********************************");        /*}catch(Exception e) {            System.out.println("-------------------------------");        }*/    }}

上面是服務端代碼

package testpackage;import java.net.*;import java.io.*;public class testsocket {    public static void main(String[] args) {        try {            Socket client=new Socket("127.0.0.1",1233);            BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));//構建一個標準輸入資料流            PrintWriter os=new PrintWriter(client.getOutputStream());            BufferedReader is=new BufferedReader(new InputStreamReader(client.getInputStream()));//由client物件建構一個輸入資料流            String readline;            System.out.println("ip為:"+client.getInetAddress()+"的用戶端連結了");            readline=sin.readLine();            while(!readline.equals("bye")) {                os.println(readline);                os.flush();                System.out.println("Client:"+readline);                System.out.println("---*****************---");                System.out.println("Server:"+is.readLine());                 readline=sin.readLine(); //從系統標準輸入讀入一字串s            }            os.close();            is.close();            client.close();        } catch (UnknownHostException e) {            // TODO Auto-generated catch block            System.out.print("====================找不到主機名稱");        } catch (IOException e) {            System.out.print("===================IO錯誤");        }            }}

上面是服務端代碼;

大家都是成年人,所以目錄結構就不用我說了吧

這隻是用java實現了一個最簡易的socket聊天,必須一問一答,而且沒有介面;

預告一下,下一篇部落格我將接介紹介面的解決方案;

談一談socket與java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.