I started to do this today. Because it was modified based on a previous small project and not from scratch, I cannot share all the code. Here I will record my daily ideas, I hope to give some suggestions to those who need them.
The idea is actually the content of the previous blog. It improved the code and sent a sentence from android to the server. Then the server sent the sentence back.
The subsequent work should not be too difficult to achieve such normal communication. The following describes the main code.
The first is the server, which uses two classes, one MyServer, to process messages sent from android; the other is ServerThread. Each time MyServer receives a user request, one ServerThread is enabled for processing.
MyServer:
Package server; import java. io. IOException; import java.net. serverSocket; import java.net. socket; public class MyServer {ServerSocket server = null; public MyServer () {this. startServer ();} void startServer () {int I = 0; try {server = new ServerSocket (8888, 3); System. out. println ("============ start =============="); while (true) {Socket socket = server. accept (); I ++; System. out. println ("Number" + I + "User connected successfully! "); New Thread (new ServerThread (socket). start () ;}} catch (IOException e) {e. printStackTrace ();}}}
The port number is written to 8888.
ServerThread:
Package server; import java. io. dataInputStream; import java. io. dataOutputStream; import java. io. IOException; import java.net. socket; public class ServerThread implements Runnable {private Socket socket; public ServerThread (Socket socket) {this. socket = socket;} // The task is to provide services for a user @ Overridepublic void run () {try {// DataInputStreamDataInputStream in = new DataInputStream (socket. getInputStream (); // DataOutputStreamDataOutputStream out = new DataOutputStream (socket. getOutputStream (); while (true) {// read information from the client String accpet = in. readUTF (); System. out. println (accpet); out. writeUTF ("server:" + accpet) ;}} finally {// if the connection fails to be established, no socket is executed. close (); socket. close () ;}} catch (IOException e) {e. printStackTrace ();}}}
After the thread starts, it always accepts messages sent from the client and returns them to the client.
The above is the server-side content, which can process requests from multiple users at the same time.
The following is the android client code.
MainActivity:
package jason.smartdinner;import serverhelper.ClientHelper;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class MainActivity extends Activity {public static final String TAG = "MAINACTIVITY";void log(String msg) {Log.d(TAG, msg);}TextView output;EditText input;Button send;ClientHelper clientHelper;Handler handler = new Handler() {public void handleMessage(Message msg) {switch (msg.what) {case 1:Bundle b = msg.getData();String msg2 = b.getString("update");log(msg2);output.setText(msg2);break;default:break;}};};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);new Thread() {public void run() {clientHelper = new ClientHelper();}}.start();output = (TextView) findViewById(R.id.output);input = (EditText) findViewById(R.id.input);send = (Button) findViewById(R.id.send);send.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubnew Thread() {@Overridepublic void run() {// TODO Auto-generated method stubsuper.run();String message = input.getText().toString();clientHelper.send(message);String receive = clientHelper.read();log(receive);Message update = new Message();update.what = 1;Bundle bundle = new Bundle();bundle.putString("update", receive);update.setData(bundle);handler.sendMessage(update);}}.start();}});}}
You will notice that I have used several threads in it. Here, we need to note that the network connection request of android cannot be in the main thread. Otherwise, the error android. OS. NetworkOnMainThreadException will be reported.
Therefore, each thread that involves network connections is newly opened for processing. It's easy to process the interface updates.
ClientHelper:
Package serverhelper; import java. io. dataInputStream; import java. io. dataOutputStream; import java. io. IOException; import java.net. socket; import android. util. log; public class ClientHelper {public static final String TAG = "CLIENTHELPER"; void log (String msg) {Log. d (TAG, msg);} DataInputStream in; DataOutputStream out; Socket socket = null; public ClientHelper () {try {socket = new Socket ("192.168.1.100", 8888 ); in = new DataInputStream (socket. getInputStream (); out = new DataOutputStream (socket. getOutputStream ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} public void send (String msg) {try {out. writeUTF (msg);} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} public String read () {String accept = "information not received"; try {accept = in. readUTF (); log (accept);} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return accept ;}}
This is the class responsible for interacting with the server, sending and receiving data. The socket ip address is the local ip address of my computer, as mentioned in the previous blog.
The code will not be uploaded first. Basically, all the code designed will be posted on it. You can figure it out by yourself.
Author: jason0539
Weibo: http://weibo.com/2553717707
Blog: http://blog.csdn.net/jason0539 (reprinted please explain the source)