Android与PC通信之Socket

来源:互联网 发布:有关红酒的网络广告语 编辑:程序博客网 时间:2024/06/05 17:44

一.环境

pc端采用的是java Swing模型。Android sdk 4.3

二.pc端代码由三个类组成:




package com.example.Recevier;import java.awt.TextArea;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.Socket;class Client extends Thread {public PcReceiver server;public Socket s;public DataInputStream dis;public DataOutputStream dos;public Client(PcReceiver server) {this.server = server;}public void run() {String info = null;TextArea ta = server.getTextArea();try {info = dis.readUTF();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}ta.append("Receiving data: " + info + "\n");    }}package com.example.Recevier;import java.io.*;import java.net.*;import java.awt.*;import java.awt.event.*;public class PcReceiver {public ServerSocket ss;private TextArea ta;private Frame f;private Label start;private Panel p;public void InitializeUI() {        f = new Frame("Receiver");ta = new TextArea();start = new Label("数据接收");p = new Panel();p.setLayout(new FlowLayout());p.add(start);f.add(ta, "Center");f.add(p, "South");      f.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}});f.setSize(400, 400);f.setVisible(true);}public Client connect() {try {Client client = new Client(this);client.s = ss.accept();client.dis = new DataInputStream(client.s.getInputStream());client.dos = new DataOutputStream(client.s.getOutputStream());return client;} catch (IOException e) {e.printStackTrace();return null;}}public TextArea getTextArea() {return ta;}public void Clientclose(Client client) {try {client.dis.close();client.dos.close();client.s.close();} catch (IOException e) {e.printStackTrace();}}}package com.example.Recevier;import java.io.IOException;import java.net.ServerSocket;public class Demo1 {public static void main(String[] args) throws IOException {// TODO Auto-generated method stubPcReceiver receiver = new PcReceiver();receiver.InitializeUI();receiver.ss = new ServerSocket(7100);while(true) {Client client = receiver.connect();if(client!=null) {    client.start();      }}}}

Android 端:简明扼要的满足的要求,界面比较粗糙:因为android跟大多数GUI库一样,是UI单线程,为了避免socket通信引起app没有反应而被系统停掉,我们需要另开一个线程来进行通信。当然此处没有设计到UI控件值的更新,所有可以不用handler。现在对handler还是用不太熟。


布局文件:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".ClientActivity" >    <EditText        android:id="@+id/EditText1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="请输入你要发送的信息" />    <Button        android:id="@+id/button1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/EditText1"        android:layout_centerHorizontal="true"        android:text="发送" /></RelativeLayout>


ClientActivity:

package com.example.serversocket;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.Socket;import java.net.UnknownHostException;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class ClientActivity extends Activity implements OnClickListener {MyThread ClientThread;EditText result;Button b1;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);result = (EditText) findViewById(R.id.EditText1);b1 = (Button) findViewById(R.id.button1);b1.setOnClickListener(this);// TODO Auto-generated method stub}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}private class MyThread extends Thread {private String message;private DataInputStream dis;private DataOutputStream dos;private Socket clientSocket;        public void setMessage(String message) {this.message = message;}@Overridepublic void run() {try {clientSocket = new Socket("10.0.2.2", 7100);dis = new DataInputStream(clientSocket.getInputStream());dos = new DataOutputStream(clientSocket.getOutputStream());} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}try {dos.writeUTF(message);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}this.close();}public void close() {try {dos.close();dis.close();clientSocket.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubClientThread = new MyThread();ClientThread.setMessage(result.getText().toString());ClientThread.start();Toast.makeText(this,result.getText().toString(), Toast.LENGTH_SHORT).show();}@Overridepublic void onBackPressed() {// TODO Auto-generated method stubfinish();super.onBackPressed();}}
运行结果截图:


1.Android段:




2.PC端:




Android socket 的一个小demo就结束了~

0 0