In network transmission, socket is a common transmission method.
The following describes the socket in android.
Socket programming generally requires two parts: client and server.
First, paste the server-side code. The specific explanation is annotated in the code. Because the TCP protocol and UDP protocol code are different, some of the Code is commented out, but they are all for test. No problem
=========== 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 (); // enable the thread
}
}
Class ServerThread extends Thread {
/*
@ Override
Public void run (){
Try {
// Create an initramsocket object and specify the listening port
DatagramSocket socket = new DatagramSocket (3333 );
Byte data [] = new byte [1024];
// Receives the data packet sent by udp and creates an empty DatagramPacket object
DatagramPacket packet = new DatagramPacket (data, data. length );
// Use the receive method to receive data sent by the client
Socket. receive (packet );
System. out. println (packet. getLength ());
String result = new String (packet. getData (), packet. getOffset (), packet. getLength ());
System. out. println ("result --->" + result );
} Catch (Exception e ){
E. printStackTrace ();
}
}
*/
@ Override
Public void run () {// TCP receive
// Declare a serverSocket object
ServerSocket serverSocket = null;
Try {
// Create a serverSocket object and have the socket listen to port 3333
ServerSocket = new ServerSocket (3333 );
// Call the accept method of serverSocker to receive requests sent by the client
Socket socket = serverSocket. accept ();
// Obtain 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" type = "codeph" text = "/codeph">
<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> <! -- Make sure you have the permission setting -->
</Manifest>
The above are the server-side code. The following two are the client-side code. The client is only a main function and a simple java project.
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 {
/**
* @ Param args
*/
Public static void main (String [] args ){
OutputStream outputStream = null;
Try {
// Create a socket object and specify the Server ip address and port
Socket socket = new Socket ("192.168.0.100", 3333 );
// Use InputStream to read files on the hard disk
InputStream inputStream = new FileInputStream ("C: // Users/Administrator/Desktop/aa.txt ");
// Obtain outputstream from socket
OutputStream = socket. getOutputStream (); // note that the outputstream package should not be incorrect.
Byte [] buffer = new byte [4*1024];
Int temp = 0;
// Extract data from inputstream and write it to 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 {
/**
* @ Param args
*/
Public static void main (String [] args ){
Try {
// Create an initramsocket object and specify the listening port
DatagramSocket socket = new DatagramSocket (3333 );
// Create an InetAddress
InetAddress serverAddress = InetAddress. getByName ("192.168.0.100 ");
String str = "hello ";
Byte data [] = str. getBytes ();
// Create an initrampacket object and specify the packet to be sent to that network and port.
DatagramPacket packet = new DatagramPacket (data, data. length, serverAddress, 3333 );
Socket. send (packet );
} Catch (Exception e ){
E. printStackTrace ();
}
}
}