Realization of Android and socket communication under LAN

Because the recent laboratory project requires that the android app data be sent to winsock for saving under the local area network, so I have done a simple study of this. Because the pc terminal is made by another classmate, I will not explain it.

On the android side, first add the permission:

    <uses-permission android:name="android.permission.INTERNET"/>  

 Then simply design the app interface - main.xml:

    <LinearLayout  
            android:orientation="horizontal"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content">  
            <!-- Defines a text box that accepts user input -->  
            <EditText  
                android:id="@+id/input"  
                android:layout_width="280dp"  
                android:layout_height="wrap_content" android:inputType=""/>  
            <Button  
                android:id="@+id/send"  
                android:layout_width="match_parent"  
                android:layout_height="wrap_content"  
                android:paddingStart="8dp"  
                android:text="@string/send"/>  
        </LinearLayout>  
        <!-- defines a text box that displays information from the server -->  
        <TextView  
            android:id="@+id/show"  
            android:layout_width="match_parent"  
            android:layout_height="match_parent"  
            android:gravity="top"  
            android:background="#ffff"  
            android:textSize="14sp"  
            android:textColor="#f000"/>  

 The interface is as follows:

Create ClientThread.java to realize the transmission of data under the local area network:

public class ClientThread implements Runnable
{
	private Socket s;
	// Define the Handler object that sends messages to the UI thread
	private Handler handler;
	// Define the Handler object that receives messages from the UI thread
	public Handler revHandler;
	// The input stream corresponding to the Socket handled by this thread
	BufferedReader br = null;
	OutputStream os = null;
	public ClientThread(Handler handler)
	{
		this.handler = handler;
	}
	public void run()
	{
		try
		{
			s = new Socket("192.168.1.133", 8040);
			br = new BufferedReader(new InputStreamReader(
					s.getInputStream()));
			os = s.getOutputStream();
			// Start a child thread to read the data from the server response
			new Thread()
			{
				@Override
				public void run()
				{
					String content = null;
					// Keep reading the content of the Socket input stream
					try
					{
						while ((content = br.readLine()) != null)
						{
							// Whenever data is read from the server, send a message to notify the program
							// The interface displays the data
							Message msg = new Message();
							msg.what = 0x123;
							msg.obj = content.toString();
							handler.sendMessage(msg);
						}
					}
					catch (IOException e)
					{
						e.printStackTrace ();
					}
				}
			}.start();
			// Initialize Looper for the current thread
			Looper.prepare();
			// Create revHandler object
			revHandler = new Handler ()
			{
				@Override
				public void handleMessage(Message msg)
				{
					// Receive data entered by the user in the UI thread
					if (msg.what == 0x345)
					{
						// Write the content entered by the user in the text box to the network
						try
						{
							os.write((msg.obj.toString() + "\r\n")
									.getBytes("utf-8"));
						}
						catch (Exception e)
						{
							e.printStackTrace ();
						}
					}
				}
			};
			// start Looper
			Looper.loop();
		}
		catch (SocketTimeoutException e1)
		{
			System.out.println("Network connection timed out!!");
		}
		catch (Exception e)
		{
			e.printStackTrace ();
		}
	}
}

 Finally, create MainActivity.java to realize functions such as acquiring the content sent in the app:

public class MainActivity extends Activity
{
	// Define two text boxes on the interface
	EditText input;
	TextView show;
	// define a button on the interface
	Button send;
	Trades trades;
	// Define the child thread that communicates with the server
	ClientThread clientThread;
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate (savedInstanceState);
		setContentView(R.layout.main);
		input = (EditText) findViewById(R.id.input);
		send = (Button) findViewById(R.id.send);
		show = (TextView) findViewById(R.id.show);
		handler = new Handler () // ②
		{
			@Override
			public void handleMessage(Message msg)
			{
				// if the message is from a child thread
				if (msg.what == 0x123)
				{
					// Append the read content to the text box
					show.append("\n" + msg.obj.toString());
				}
			}
		};
		clientThread = new ClientThread(handler);
		// The client starts the ClientThread thread to create a network connection and read data from the server
		new Thread(clientThread).start(); // ①
		send.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				try
				{
					// When the user presses the send button, encapsulate the data entered by the user into a Message
					// Then send to the Handler of the child thread
					Message msg = new Message();
					msg.what = 0x345;
					msg.obj = input.getText().toString();
					clientThread.revHandler.sendMessage (msg);
					// clear the input text box
					input.setText("");
				}
				catch (Exception e)
				{
					e.printStackTrace ();
				}
			}
		});
	}
}

 In this way, the function we want to transmit data to the pc is achieved.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325171083&siteId=291194637