最近在學習Android關於網絡編程的知識,在這個過程中也遇到了不少問題,這篇文章是android基於socket的網絡編程,能讓人更好的了解網絡編程底層的相關知識。其他話就不說了,直接看代碼吧。
服務器端采用的是圖形化界面:
- package com.app.qrs;
-
- import java.awt.Container;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.io.OutputStream;
- import java.net.InetAddress;
- import java.net.ServerSocket;
- import java.net.Socket;
-
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- import javax.swing.JTextField;
-
- class Myserver extends JFrame implements ActionListener{
- public static final String Server_Message = "服務器發布的信息:";
- private JTextField messagetext;
- private JButton ok;
- public static String servermsg = "hello android Client! 我是該程序的程序員:吳偉棟!";
- public Myserver()
- {
- super("信息發布");
- Container c = getContentPane();
- JPanel panel = new JPanel();
- JLabel lablename = new JLabel(Server_Message);
- messagetext = new JTextField(30);
- messagetext.addActionListener(this);
- panel.add(lablename);
- panel.add(messagetext);
- ok = new JButton("確定");
- ok.addActionListener(this);
- panel.add(ok);
- c.add(panel);
- }
- public static ServerSocket server;
- /**
- * @param args
- */
- public static void main(String[] args) {
- Myserver ms = new Myserver();
- ms.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- ms.setSize(280, 160);
- ms.setVisible(true);
-
- try
- {
-
- server = new ServerSocket(10000);
- System.out.println(InetAddress.getLocalHost());
- while(true)
- {
- System.out.println("------------->"+servermsg);
- Socket socket = server.accept();
- OutputStream out = socket.getOutputStream();
- String msg = servermsg;
- out.write(msg.getBytes());
- socket.close();
- }
- }catch(Exception e)
- {
- e.printStackTrace();
- }
- // TODO Auto-generated method stub
-
- }
- @Override
- public void actionPerformed(ActionEvent e) {
- /*
- *
- * 數據緩存解決了客服端存在中間一段黑屏的效果
- * 即在客服端第一次點擊刷新按鈕時會有黑屏效果
- * 第二次才能出現信息。
- * 但在客服端還是存在bug(服務器未更新信息,客服端多次刷新的時候)
- * **/
- String servermsgbuffer = new String();
- servermsgbuffer=messagetext.getText();
- servermsg = servermsgbuffer;
-
- }
- }