What is a socket?
The so-called socket is also commonly referred to as "socket", used to describe the IP address and port, is a communication of the handle, the application usually through the "socket" to the network to send requests or answer network requests, it is the network communication process endpoints in the abstract representation. It consists mainly of the following two agreements:
TCP (Transmission Control Protocol Transmission Control Protocol): Transmission Control Protocol, which provides a connection-oriented, reliable byte throttling service. Before the client and server Exchange data, a TCP connection must be established between the two parties before the data can be transferred. TCP provides timeouts, discards duplicate data, verifies data, and controls traffic to ensure that data is transferred from one end to the other.
UDP (user Datagram PROTOCL Subscriber Datagram Protocol): User Datagram Protocol, a simple transport-level protocol for datagram. UDP does not provide reliability, it simply sends the application to the IP layer, but it does not guarantee that it will reach its destination. Because UDP does not have to establish a connection between the client and the server before transmitting the datagram, and does not have the mechanism such as the time-out, the transmission speed is very fast.
Detailed explanations are as follows:
TCP transmission and UDP are not the same, TCP transport is streaming, you must first establish a connection, and then the data flow along the connected line (virtual circuit) transmission. As a result, TCP data streams are not like UDP datagrams, and each datagram contains destination addresses and ports because each datagram is routed separately. The TCP transport only needs to specify the destination address and port when establishing the connection.
Figuratively speaking, TCP is like a phone call, and UDP is like a telegram. On the macro level, UDP is not divided into client and server. The two sides of communication are equal. Micro-only relative to a message, the sender is the client, the listener end is the server. Sending the datagram to the router is like sending a telegram to the post office, and the thing behind it is that the sender has no control over it, and it is unknown. Therefore, it is unreliable, there may be loss of the message and unknown. Just as every telegram has to have a recipient, each datagram has a destination address and a port.
TCP is a client-and server-side connection each time. The initiator of the connection (rather than the person who dialed the call) is the client, and the listener (equivalent to the person who is waiting to answer the phone on the phone) is the server. The initiator specifies the server address and port (equivalent to dialing) to be connected, and the listener establishes the connection by shaking hands with the initiator three times (equivalent to hearing the phone ringing to answer the phone). After the connection is established, both parties can send and receive data from each other (telephone).
Java how to manipulate the socket?
It is worth mentioning that Java provides the corresponding class for TCP and UDP, respectively, TCP is a java.net two classes of socket and serversocket, respectively, to represent two-way connected client and server. This is two very good packaged class, easy to use! UDP is Java.net.DatagramSocket.
127.0.0.1 is the loop address, used for testing, the equivalent of localhost native address, no network card, no DNS can be accessed, port address between 0~65535, where 0~1023 between the port is used for some well-known network services and applications, A user's normal network application should use more than 1024 ports.
The socket communication model is as follows:
If you have the Java socket programming and Fuzzy place to review (http://blog.csdn.net/shimiso/article/details/8529941), this article does not repeat, the following we use the most commonly used TCP protocol examples:
Server, using ServerSocket to listen to the specified port, the port can be arbitrarily specified (because the port under 1024 is usually reserved port, in some operating systems are not free to use, so it is recommended to use a port greater than 1024), waiting for customer connection request, after the client connected, the session generated , and close the connection after the session completes.
Client, use Java socket communication to issue a connection request to one of the servers on the network, open the session once the connection is successful, and close the socket after the session completes. The client does not need to specify an open port, typically temporarily, dynamically allocating more than 1024 ports.
TCP Network Connectivity Model:
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/
Android client program Generation analysis:
Uploadactivity.java package com.android.upload;
Import Java.io.File;
Import Java.io.OutputStream;
Import Java.io.PushbackInputStream;
Import Java.io.RandomAccessFile;
Import Java.net.Socket;
Import android.app.Activity;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.ProgressBar;
Import Android.widget.TextView;
Import Android.widget.Toast;
Import Com.android.service.UploadLogService;
Import Com.android.socket.utils.StreamTool;
public class Uploadactivity extends activity {private EditText filenametext;
Private TextView Resulview;
Private ProgressBar Uploadbar;
Private Uploadlogservice Logservice; Private Boolean start=True
Private Handler Handler = new Handler () {@Override public void Handlemessage (msg) {
int length = Msg.getdata (). GETINT ("size");
uploadbar.setprogress (length);
float num = (float) uploadbar.getprogress ()/(float) uploadbar.getmax ();
int result = (int) (NUM * 100);
Resulview.settext (result+ "%"); if (Uploadbar.getprogress () ==uploadbar.getmax ()) {Toast.maketext (Uploadactivity.this, R.string.success,
1). Show ();
}
}
};
@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Logservice = new Uploadlogservice (this);
Filenametext = (edittext) This.findviewbyid (r.id.filename); Uploadbar = (ProgressBar) This.findviewbyid (R.id.uploadbar);
Resulview = (TextView) This.findviewbyid (R.id.result);
Button button = (button) This.findviewbyid (R.id.button);
Button button1 = (button) This.findviewbyid (r.id.stop); Button1. Setonclicklistener (New Onclicklistener () {@Override public void OnC
Lick (View v) {start=false;
}
}); Button.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v)
{start=true;
String filename = Filenametext.gettext (). toString (); if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {File UploadFile = new
File (Environment.getexternalstoragedirectory (), filename);
if (uploadfile.exists ()) {uploadfile (uploadfile); }else{
Toast.maketext (Uploadactivity.this, R.string.filenotexsit, 1). Show (); }else{Toast.maketext (Uploadactivity.this, R.string.sdcarderror, 1). Show ()
;
}
}
});
/** * Upload file * @param uploadfile * * private void UploadFile (final file uploadfile) {
New Thread (New Runnable () {@Override public void run () {
try {uploadbar.setmax (int) uploadfile.length ());
String Souceid = Logservice.getbindid (UploadFile);
String head = "content-length=" + uploadfile.length () + "; Filename=" + uploadfile.getname () + "; sourceid=" + (Souceid==null?)
"": Souceid) + "\ r \ n";
Socket socket = new Socket ("192.168.1.78", 7878);OutputStream OutStream = Socket.getoutputstream ();
Outstream.write (Head.getbytes ());
Pushbackinputstream instream = new Pushbackinputstream (Socket.getinputstream ());
String response = Streamtool.readline (instream);
string[] items = Response.split (";");
String Responseid = items[0].substring (items[0].indexof ("=") +1);
String position = items[1].substring (items[1].indexof ("=") +1);
if (souceid==null) {//Representative has not previously uploaded this file, add a binding record to the database Logservice.save (Responseid, UploadFile);
} randomaccessfile Fileoutstream = new Randomaccessfile (UploadFile, "R");
Fileoutstream.seek (integer.valueof (position));
byte[] buffer = new byte[1024];
int len =-1; int length = integer.valueof (position); while (start&& (len = fileoutstream.read (buffer))!=-1) {outstream.write (buffer, 0, Len
);
length = = Len;
msg = new Message ();
Msg.getdata (). Putint ("size", length);
Handler.sendmessage (msg);
} fileoutstream.close ();
Outstream.close ();
Instream.close ();
Socket.close ();
if (Length==uploadfile.length ()) Logservice.delete (UploadFile);
catch (Exception e) {e.printstacktrace ();
}}). Start ();
}} Streamtool.java package com.android.socket.utils;
Import Java.io.ByteArrayOutputStream; Import Java.io.FiLe
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.PushbackInputStream;
public class Streamtool {public static void save (file file, byte[] data) throws Exception {
FileOutputStream OutStream = new FileOutputStream (file);
Outstream.write (data);
Outstream.close (); public static String ReadLine (Pushbackinputstream in) throws IOException {char buf[] =
New char[128];
int room = Buf.length;
int offset = 0;
int C;
Loop:while (TRUE) {switch (c = in.read ()) {case-1:
Case ' \ n ': Break loop;
Case ' \ r ': int c2 = In.read ();
if ((C2!= ' \ n ') && (C2!=-1)) In.unread (C2);
Break loop; Default:if (--room < 0) {char[] Linebuffer =
Buf
BUF = new Char[offset + 128];
room = buf.length-offset-1;
System.arraycopy (linebuffer, 0, buf, 0, offset);
} buf[offset++] = (char) c;
Break
} if ((c = = 1) && (offset = 0)) return null;
Return string.copyvalueof (buf, 0, offset); /** * Read Stream * @param instream * @return byte array * @throws Exception/Public Static byte[] Readstream (InputStream instream) throws exception{bytearrayoutputstream Outsteam = new Bytear
Rayoutputstream ();
byte[] buffer = new byte[1024];
int len =-1; While(Len=instream.read (buffer))!=-1) {outsteam.write (buffer, 0, Len);
} outsteam.close ();
Instream.close ();
return Outsteam.tobytearray ();
}} Uploadlogservice.java package com.android.service;
Import Java.io.File;
Import Android.content.Context;
Import Android.database.Cursor;
Import Android.database.sqlite.SQLiteDatabase;
public class Uploadlogservice {private Dbopenhelper dbopenhelper;
Public Uploadlogservice {this.dbopenhelper = new Dbopenhelper (context); } public void Save (String SourceID, File uploadfile) {Sqlitedatabase db = Dbopenhelper.getwrita
Bledatabase (); Db.execsql ("INSERT into Uploadlog (Uploadfilepath, SourceID) VALUES (?,?)", New Object[]{uploadfile.getabs
Olutepath (), SourceID}); public void Delete (File UploadfiLe) {Sqlitedatabase db = Dbopenhelper.getwritabledatabase ();
Db.execsql ("Delete from Uploadlog where uploadfilepath=?", New Object[]{uploadfile.getabsolutepath ()); Public String Getbindid (File uploadfile) {Sqlitedatabase db = Dbopenhelper.getreadabledatabas
E (); Cursor Cursor = Db.rawquery ("Select SourceID from Uploadlog where uploadfilepath=?", New String[]{uploa
Dfile.getabsolutepath ()});
if (Cursor.movetofirst ()) {return cursor.getstring (0);
return null;
}} Dbopenhelper.java package com.android.service;
Import Android.content.Context;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.database.sqlite.SQLiteOpenHelper; public class Dbopenhelper extends Sqliteopenhelper {public Dbopenhelper (context) {super (C
Ontext, "upload.db", NULL, 1); } @Override
public void OnCreate (Sqlitedatabase db) {db.execsql ("CREATE TABLE uploadlog" (_id Integer PRIMARY key Autoi
Ncrement, Uploadfilepath varchar (MB), SourceID varchar (10)) "); @Override public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {Db.execs
QL ("DROP TABLE IF EXISTS uploadlog");
OnCreate (DB); } main.xml <?xml version= "1.0" encoding= "Utf-8"?> <linearlayout "xmlns:android=" P://schemas.android.com/apk/res/android "android:orientation=" vertical "android:layout_width=" fill_parent "and roid:layout_height= "Fill_parent" > <textview android:layout_width= "fill_parent" android:layout_he ight= "Wrap_content" android:text= "@string/filename"/> <edittext android:layo Ut_width= "Fill_parent" android:layout_height= "wrap_content" android:text= "022.jpg" android:id= "@ +Id/filename "/> <button android:layout_width=" wrap_content "Andro"
id:layout_height= "Wrap_content" android:text= "@string/button" android:id= "@+id/button"/> <button android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Andro id:text= "Pause" android:id= "@+id/stop"/> <progressbar android:layout_width= "fill
_parent "android:layout_height=" 20px "style="? Android:attr/progressbarstylehorizontal "
Android:id= "@+id/uploadbar"/> <textview android:layout_width= "Fill_parent"
android:layout_height= "wrap_content" android:gravity= "center" android:id= "@+id/result"/> </LinearLayout> androidmanifest.xml <?xml version= "1.0" encoding= "Utf-8"?> <manife St Xmlns:android= "http://schemas.android.com/apk/res/android "package=" Com.android.upload "android:versioncode=" 1 "android:versionname = "1.0" > <uses-sdk android:minsdkversion= "8"/> <application Android:icon = "@drawable/ic_launcher" android:label= "@string/app_name" > <activity android:name= " . Uploadactivity "android:label=" @string/app_name "> <intent-filter> &L T;action android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.inte"
Nt.category.LAUNCHER "/> </intent-filter> </activity> </application> <!--permissions to access the network--> <uses-permission android:name= "Android.permission.INTERNET"/> <!--in SDCA Create and delete file permissions in rd--> <uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> < !--Write data permissions to SDcard; <uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> </manifest>
Java Service side: