ANDROID_MARS学习笔记_S01原始版_015_Socket

一、代码
1.xml
(1)main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="fill_parent"
 5     android:layout_height="fill_parent"
 6     >
 7 <Button 
 8     android:id="@+id/startListener"
 9     android:layout_width="fill_parent" 
10     android:layout_height="wrap_content" 
11     android:text="启动监听线程"
12     />
13 </LinearLayout>

 

(2)AndroidManifest.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.socket"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6 
 7     <uses-sdk
 8         android:minSdkVersion="8"
 9         android:targetSdkVersion="21" />
10 
11     <application
12         android:allowBackup="true"
13         android:icon="@drawable/ic_launcher"
14         android:label="@string/app_name"
15         android:theme="@style/AppTheme" >
16         <activity
17             android:name=".SocketActivity"
18             android:label="@string/app_name" >
19             <intent-filter>
20                 <action android:name="android.intent.action.MAIN" />
21 
22                 <category android:name="android.intent.category.LAUNCHER" />
23             </intent-filter>
24         </activity>
25     </application>
26     <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
27     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
28     <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
29     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
30     <uses-permission android:name="android.permission.INTERNET"/>
31 </manifest>

 

2.java
(1)SocketActivity.java

 1 package com.socket;
 2 
 3 import java.net.DatagramPacket;
 4 import java.net.DatagramSocket;
 5 
 6 import android.app.Activity;
 7 import android.os.Bundle;
 8 import android.view.View;
 9 import android.view.View.OnClickListener;
10 import android.widget.Button;
11 
12 public class SocketActivity extends Activity {
13     /** Called when the activity is first created. */
14     private Button startButton = null;
15     @Override
16     public void onCreate(Bundle savedInstanceState) {
17         super.onCreate(savedInstanceState);
18         setContentView(R.layout.main);
19         startButton = (Button)findViewById(R.id.startListener);
20         startButton.setOnClickListener(new StartSocketListener());
21     }
22     
23     class StartSocketListener implements OnClickListener{
24 
25         @Override
26         public void onClick(View v) {
27             new ServerThread().start();
28         }
29         
30     }
31     
32     //运行时要注释掉一个run方法
33     class ServerThread extends Thread{
34         public void run(){
35             //声明一个ServerSocket对象
36             ServerSocket serverSocket = null;
37             try {
38                 //创建一个ServerSocket对象,并让这个Socket在4567端口监听
39                 serverSocket = new ServerSocket(4567);
40                 //调用ServerSocket的accept()方法,接受客户端所发送的请求,是阻塞方法
41                 Socket socket = serverSocket.accept();
42                 //从Socket当中得到InputStream对象
43                 InputStream inputStream = socket.getInputStream();
44                 byte buffer [] = new byte[1024*4];
45                 int temp = 0;
46                 //从InputStream当中读取客户端所发送的数据
47                 while((temp = inputStream.read(buffer)) != -1){
48                     System.out.println(new String(buffer,0,temp));
49                 }
50             } catch (IOException e) {
51                 // TODO Auto-generated catch block
52                 e.printStackTrace();
53             }
54             finally{
55                 try {
56                     serverSocket.close();
57                 } catch (IOException e) {
58                     // TODO Auto-generated catch block
59                     e.printStackTrace();
60                 }
61             }
62         
63         }
64         public void run(){
65             try {
66                 //创建一个DatagramSocket对象,并指定监听的端口号
67                 DatagramSocket socket = new DatagramSocket(4567);
68                 byte data [] = new byte[1024];
69                 //创建一个空的DatagramPacket对象,用来接收数据,udp是一个包一个包接收的,没有流的概念
70                 DatagramPacket packet = new DatagramPacket(data,data.length);
71                 //使用receive方法接收客户端所发送的数据,也是阻塞方法
72                 socket.receive(packet);
73                 String result = new String(packet.getData(),packet.getOffset(),packet.getLength());
74                 System.out.println("result--->" + result);
75             } catch (Exception e) {
76                 // TODO Auto-generated catch block
77                 e.printStackTrace();
78             }
79         }
80     }
81 }

 

(2)TCPClient.java

 1 package com.client;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.InputStream;
 5 import java.io.OutputStream;
 6 import java.net.Socket;
 7 
 8 public class TCPClient{
 9     public static void main(String[] args){
10         try{
11             //创建一个Socket对象,指定服务器端的IP地址和端口号
12             Socket socket = new Socket("localhost",4567);
13             //使用InputStream读取硬盘上的文件
14             InputStream inputStream = new FileInputStream("D://LoseYourself.lrc");
15             //从Socket当中得到OutputStream
16             OutputStream outputStream = socket.getOutputStream();
17             byte[] buffer = new byte[4*1024];
18             int temp = 0;
19             //将InputStream当中的数据取出,并写入到OutputStream当中
20             while((temp = inputStream.read(buffer))!=-1){
21                 outputStream.write(buffer,0,temp);
22             }
23             outputStream.flush();
24         }catch(Exception e){
25             e.printStackTrace();
26         }
27     }
28 }

 

(3)UDPClient.java

 1 package com.client;
 2 
 3 import java.net.DatagramPacket;
 4 import java.net.DatagramSocket;
 5 import java.net.InetAddress;
 6 import java.net.UnknownHostException;
 7 
 8 public class UDPClient {
 9     public static void main(String[] args) throws UnknownHostException {
10         System.out.println(">>> --UDPClient-- >>>>>>>>>>>>>>");
11         
12         // 首先创建一个DatagramSocket对象
13         DatagramSocket socket;
14         try {
15             socket = new DatagramSocket(4567);
16             // 创建一个InetAddress,代表网络的一个地址
17             InetAddress serverAddress = InetAddress.getByName("192.168.1.104");
18             String str = "hello socket";
19             byte data[] = str.getBytes();
20             // 创建一个DatagramPacket对象,并指定要将这个数据包发送的网络的哪个地址和端口
21             DatagramPacket packet = new DatagramPacket(data, data.length,
22                     serverAddress, 4567);
23             // 调用socket对象的send方法,发送数据
24             socket.send(packet);
25         } catch (Exception e) {
26             e.printStackTrace();
27         }
28     }
29 }

 

你可能感兴趣的:(ANDROID_MARS学习笔记_S01原始版_015_Socket)