在网络传输中socket是很常见的传输方式。
下面介绍一下android中的socket。
socket编程一般需要两个部分,分别为客户端和服务器端。
先贴出服务器端的代码,具体解释在代码中有注释。由于TCP协议与UDP协议的代码不同,所以部分代码注释起来了,但是都是亲测。没问题的
==========SocketServiceActivity.java=========
package com.yx.socketservice;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
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;
public class SocketServiceActivity extends Activity {
private Button startButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket_service);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new StartButtonListener());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.socket, menu);
return true;
}
class StartButtonListener implements OnClickListener{
@Override
public void onClick(View arg0) {
new ServerThread().start();//开启线程
}
}
class ServerThread extends Thread{
@Override
public void run() {//TCP接收
//声明一个serverSocket对象
ServerSocket serverSocket = null;
try {
//创建serverSocket对象,并让socket监听3333端口
serverSocket = new ServerSocket(3333);
//调用serverSocker的accept方法,接收客户端发送的请求
Socket socket = serverSocket.accept();
//获取inputstream
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024*4];
int temp = 0;
while((temp=inputStream.read(buffer))!=-1){
System.out.println(new String(buffer,0,temp));
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
=================AndroidManifest.xml===========
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yx.socketservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.yx.socketservice.SocketServiceActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission><!-- 一定要有这句,权限的设置 -->
</manifest>
以上是服务器端的代码,下面两个是客户端的代码,客户端仅仅是一个main函数,简单的java工程。
TCP:
package com.yx.forAnrdoid;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) {
OutputStream outputStream=null;
try {
//创建socket对象,指定服务器的ip和端口
Socket socket = new Socket("192.168.0.100", 3333);
//使用InputStream读取硬盘上的文件
InputStream inputStream = new FileInputStream("C://Users/Administrator/Desktop/aa.txt");
//从socket中获取outputstream
outputStream = socket.getOutputStream();//注意这里outputstream的包不要倒错
byte[] buffer = new byte[4*1024];
int temp = 0;
//将inputstream当中的数据取出,并写入到outputstream中
while((temp=inputStream.read(buffer))!=-1){
outputStream.write(buffer, 0, temp);
}
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
UDP:
package com.yx.forAnrdoid;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPClient {
public static void main(String[] args) {
try {
//创建一个DatagramSocket对象,并指定监听端口
DatagramSocket socket = new DatagramSocket(3333);
//创建一个InetAddress
InetAddress serverAddress = InetAddress.getByName("192.168.0.100");
String str = "hello";
byte data[] = str.getBytes();
//创建一个DatagramPacket对象,并指定要将那个数据包发送到那个网络和端口上
DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, 3333);
socket.send(packet);
} catch (Exception e) {
e.printStackTrace();
}
}
}