android中利用Socket实现手机客户端与PC端进行通信

时间:2021-02-11 10:11:52

1. 项目截图

  android中利用Socket实现手机客户端与PC端进行通信

 

2. 服务端源码

  

package test;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {

	// 服务器连接
	public static ServerSocket cServerSocket;

	// 连接
	public static Socket cSocket;

	// 端口
	public static final int PORT = 8888;

	/**
	 * 主方法
	 * 
	 * @time 注释时间:2013-12-23 下午4:10:47
	 * @param args
	 */
	public static void main ( String [ ] args ) {

		DataInputStream dis = null;
		DataOutputStream dos = null;	
		try {
			cServerSocket = new ServerSocket (
			                              PORT );
			while ( true ) {
				System.out.println ( "正在等待客户连接..." );
				// 这里处于等待状态,如果没有客户端连接,程序不会向下执行
				cSocket = cServerSocket.accept ( );
				dis = new DataInputStream (
				                              cSocket.getInputStream ( ) );
				dos = new DataOutputStream (
				                              cSocket.getOutputStream ( ) );
				// 读取数据
				String clientStr = dis.readUTF ( );

				// 写出数据
				dos.writeUTF ( "已收到信息:"
				                              + clientStr );
				System.out.println ( "---客户端已成功连接---" );
				// 得到客户端的IP
				System.out.println ( "客户端的IP="
				                              + cSocket.getInetAddress ( ) );
				// 得到客户端的端口号
				System.out.println ( "客户端的端口号="
				                              + cSocket.getPort ( ) );
				// 得到本地端口号
				System.out.println ( "本地服务器端口号="
				                              + cSocket.getLocalPort ( ) );
				System.out.println ( "客户端:"
				                              + clientStr );
				System.out.println ( "---------------------------------" );

			}
		}
		catch ( IOException e ) {
			e.printStackTrace ( );
		}
		finally {
			try {
				if (dis != null) {
					dis.close ( );
				}
				if (dos != null) {
					dos.close ( );
				}
			}
			catch ( IOException e ) {
				e.printStackTrace ( );
			}

		}
	}
}

 客户端源码

package com.example.cf_mysocketclient;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

	// 发送按钮
	private Button cButtonSend;

	// 发送的内容
	private EditText cEditTextContent;

	// 接收的内容
	private TextView cTextViewContent;

	// Socket用于连接服务器获取输入输出流
	private Socket cSocket;

	// 服务器server/IP地址(当前PC的IP地址)
	private final String ADDRESS = "10.0.2.2";

	// 服务器端口
	private final int PORT = 8888;

	// 消息处理的线程
	private Thread cThread;

	// 消息的内容
	private String cContent;

	// 处理消息机制
	Handler cHandler = new Handler ( ) {

		@ Override
		public void handleMessage ( Message msg ) {

			switch ( msg.what ) {
				case 0x01 :
					cThread = new Thread ( ) {

						@ Override
						public void run ( ) {

							super.run ( );
							DataInputStream dis = null;
							DataOutputStream dos = null;
							try {
								// 阻塞函数,正常连接后才会向下继续执行
								cSocket = new Socket (
								                              ADDRESS ,
								                              PORT );
								dis = new DataInputStream (
								                              cSocket.getInputStream ( ) );
								dos = new DataOutputStream (
								                              cSocket.getOutputStream ( ) );
								// 向服务器写数据
								dos.writeUTF ( cEditTextContent
								                              .getText ( )
								                              .toString ( ) );
								cContent = "I Say:";
								cContent += cEditTextContent.getText ( )
								                              .toString ( );
								cContent += "\n";
								cContent += "Server Say:";
								// 读取服务器发来的数据
								cContent += dis.readUTF ( );
							}
							catch ( UnknownHostException e ) {
								e.printStackTrace ( );
							}
							catch ( IOException e ) {
								e.printStackTrace ( );
							}
							finally {
								try {
									if (dis != null) {
										dis.close ( );
									}
									if (dos != null) {
										dos.close ( );
									}
								}
								catch ( IOException e ) {
									e.printStackTrace ( );
								}
								cHandler.sendEmptyMessage ( 0x02 );
							}
						}

					};
					cThread.start ( );
					break;
				case 0x02 :
					cTextViewContent.setText ( cContent );
					break;

				default :
					break;
			}
		}

	};

	@ Override
	protected void onCreate ( Bundle savedInstanceState ) {

		super.onCreate ( savedInstanceState );
		this.getWindow ( )
		                              .setFlags ( WindowManager.LayoutParams.FLAG_FULLSCREEN ,
		                                                            WindowManager.LayoutParams.FLAG_FULLSCREEN );
		this.requestWindowFeature ( Window.FEATURE_NO_TITLE );
		setContentView ( R.layout.activity_main );
		init ( );
	}

	/**
	 * 初始化
	 * 
	 */
	private void init ( ) {

		cButtonSend = ( Button ) findViewById ( R.id.btn );
		cEditTextContent = ( EditText ) findViewById ( R.id.et );
		cTextViewContent = ( TextView ) findViewById ( R.id.tv );
		cButtonSend.setOnClickListener ( new OnClickListener ( ) {

			@ Override
			public void onClick ( View v ) {

				cHandler.sendEmptyMessage ( 0x01 );
			}
		} );
	}

}

 布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="发送" />

    <EditText
        android:id="@+id/et"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/et_shape" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/tv_shape" />

</LinearLayout>

当用户在编辑框中输入内容,便可以在TextView中显示出来

温馨提示  :

   运行项目之前,一定要把服务端先启动 ,在运行客户端