JAVA之Socket編程__IOS

來源:互聯網
上載者:User

Socket編程就是通過Socket類來編寫網路通訊程式,對於網路通訊程式,分為兩個,一個是伺服器程式,一個是用戶端程式。伺服器程式建立一個ServerSocket對象(伺服器通訊端),通過調用accept()方法來接受來自用戶端的串連請求,用戶端程式建立一個Socket對象來串連伺服器,串連請求成功後,伺服器同時建立一個新的Socket與用戶端建立串連,伺服器繼續等待新的請求。


一、用戶端向伺服器發送訊息 伺服器端:


import java.net.*;import java.io.*;public class Server {DataInputStream din;DataOutputStream dout;ServerSocket ss;Socket sc;public Server() {try {ss = new ServerSocket(9999); //建立伺服器通訊端sc = ss.accept(); //等待來自用戶端的串連請求din = new DataInputStream(sc.getInputStream()); //擷取資料輸入流String msg = din.readUTF();System.out.println("用戶端說:" + msg);din.close();sc.close();}catch(Exception e) {e.printStackTrace();}}public static void main(String[] args) {new Server();}}


在上述伺服器端代碼中,通過accept來接收用戶端的請求,這個請求是阻塞的,也就是說,如果沒有用戶端串連進來,伺服器端就一直停留在接收狀態,即不會執行接下來的代碼,當用戶端串連進來之後,通過資料輸入流來讀取用戶端發來的訊息,然後輸出,結束時需關閉IO流和Socket。 用戶端:

import java.net.*;import java.io.*;public class Client {DataInputStream din;DataOutputStream dout;Socket sc;public Client() {try {sc = new Socket("127.0.0.1", 9999); //串連伺服器dout = new DataOutputStream(sc.getOutputStream()); //擷取資料輸出資料流String msg = "hello server";dout.writeUTF(msg);dout.close();sc.close();} catch(Exception e) {e.printStackTrace();}}public static void main(String[] args) {new Client();}}

在上述用戶端代碼中也一樣,通過Socket來串連伺服器,串連成功後對伺服器放送訊息,結束時也需要關閉IO流和Socket。

上述程式,是簡單的用戶端向伺服器發送訊息,也就是一個簡單的單向通訊的程式。


二、伺服器端和用戶端互發訊息


上面的只是用戶端對伺服器發送訊息,現在來看一下兩者之間可以互發訊息的程式。 伺服器端:

import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.net.*;import java.io.*;public class ChatServer extends JFrame implements ActionListener {JButton jb = new JButton("發送");JTextField jtf = new JTextField(20);JTextArea jta = new JTextArea();JScrollPane jsp = new JScrollPane(jta);JPanel jp = new JPanel();PrintWriter pw = null;public ChatServer() {this.setTitle("伺服器端");this.setSize(350, 250);this.setResizable(false);this.setVisible(true);this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);this.setLocation(500, 300);jta.setDisabledTextColor(Color.black);jb.addActionListener(this);jp.add(jtf);jp.add(jb);jta.setEnabled(false);this.add(jsp);this.add(jp,"South");try {ServerSocket ss = new ServerSocket(9999);Socket s = ss.accept();InputStreamReader isr = new InputStreamReader(s.getInputStream());BufferedReader br = new BufferedReader(isr);pw = new PrintWriter(s.getOutputStream(), true);while(true) {String xinxi = br.readLine();jta.append("用戶端說:" + xinxi + "\n\r");}}catch(Exception e) {e.printStackTrace();}}public void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif(e.getSource() == jb) {String xinxi = jtf.getText();jta.append("我對用戶端說:" + xinxi + "\n\r");pw.println(xinxi);jtf.setText("");}}public static void main(String[] args) {// TODO Auto-generated method stubnew ChatServer();}}

用戶端:

import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.net.*;import java.io.*;public class ChatClient extends JFrame implements ActionListener {JButton jb = new JButton("發送");JTextField jtf = new JTextField(20);JTextArea jta = new JTextArea();JScrollPane jsp = new JScrollPane(jta);JPanel jp = new JPanel();PrintWriter pw = null;DataInputStream din;DataOutputStream dout;public ChatClient() {this.setTitle("用戶端");this.setSize(350, 250);this.setResizable(false);this.setVisible(true);this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);this.setLocation(500, 300);jta.setDisabledTextColor(Color.black);jb.addActionListener(this);jp.add(jtf);jp.add(jb);jta.setEnabled(false);jta.setLineWrap(true);this.add(jsp);this.add(jp,"South");jtf.addKeyListener(new KeyListener() {@Overridepublic void keyTyped(KeyEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void keyReleased(KeyEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void keyPressed(KeyEvent e) {int key = e.getKeyCode();if(key == 10) {String xinxi = jtf.getText();jta.append("我對伺服器說:" + xinxi + "\r\n");try {dout.writeUTF(xinxi);} catch (IOException e1) {e1.printStackTrace();}jtf.setText("");}}});try {Socket s = new Socket("127.0.0.1", 8888);din = new DataInputStream(s.getInputStream());dout = new DataOutputStream(s.getOutputStream());while(true) {String xinxi = din.readUTF();jta.append("伺服器說:" + xinxi + "\r\n");}}catch(Exception e) {e.printStackTrace();}}public void actionPerformed(ActionEvent e) {if(e.getSource() == jb) {String xinxi = jtf.getText();if(!xinxi.equals("")) {jta.append("我對伺服器說:" + xinxi + "\r\n");try {dout.writeUTF(xinxi);} catch (IOException e1) {e1.printStackTrace();}jtf.setText("");}else {}}}public static void main(String[] args) {new ChatClient();}}


上述代碼寫的就是伺服器端和用戶端可以互發訊息的一個程式,通過一個while死迴圈來不斷接收來自用戶端或者伺服器端的訊息,並且輸出到JTextArea的文本域中,輸入訊息則是通過讀取文字框中的內容,通過一個按鈕將他發送到伺服器端或者用戶端,兩段代碼其實差的不多。


三、多個用戶端同時串連到伺服器端


一個伺服器只能接收一個來自用戶端的請求,這顯然是不能滿足我們的要求的,那麼,如何來實現多個用戶端同時串連到伺服器端呢。這就要用到線程了,每當伺服器接收到一個來自用戶端的請求時,我們就建立一個線程,讓這個線程去處理該用戶端,我們可以這樣做:

while(flag) {try {Socket sc = ss.accept();ServerThread st = new ServerThread(sc);st.start();}catch(Exception e) {e.printStackTrace();}}
這樣就可以處理多用戶端同時串連伺服器端的問題了。但是呢。我們想要用戶端與用戶端之間發送訊息該怎麼辦呢。那麼就需要伺服器端這個橋樑,一個用戶端把訊息發送到伺服器端,伺服器端再把訊息發送到另一個用戶端,那麼伺服器怎麼知道我想要發送的訊息是發送到這個用戶端呢。那麼可以這麼做,我們建立一個Vector對象用來儲存當前串連到伺服器端的線程,然後當一個用戶端想要發送訊息給另一個用戶端時,通過遍曆Vector來找到那個用戶端,然後就可以發送給那個用戶端訊息了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.