安卓的socket实现

安卓实现socket通信,采用的是服务器用eclipse运行,客户端在安卓手机上运行。


在手机上输入信息可以在电脑上显示,需要手机和电脑连接同一个局域网,可以手机开热点,电脑连接热点,就处于同一局域网。


需要在AndroidManifest.xml添加权限

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

服务器代码:

package com.socket;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        Socket socket=null;                    //定义接受用的socket
        try {
            ServerSocket serversocket=new ServerSocket(9998); //创建服务器类,设置端口,以连接客户端进行通信
            while(true) {
                System.out.println("服务器启动,等待客户端连接");
                socket=serversocket.accept();                   //接收客户端传来的socket,赋值给本地socket
                System.out.println("cooncet success");         //显示是否连接成功
                ServerThread serverthread=new ServerThread(socket); //创建多线程类把socket传入
                serverthread.start();                                //开始线程
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}

多线程的代码:

package com.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerThread extends Thread{     //自定义线程类继承Thread类
	Socket socket=null;                    //定义本地的socket
	public ServerThread(Socket socket) {  //用构造方法对本地的socket赋值
		this.socket=socket;
	}
	public void run() {                 //重写run方法
		try {
			InputStream is=socket.getInputStream();  //定义输入流用来接收socket的
			InputStreamReader isr=new InputStreamReader(is);//把字节流转成字符流
			BufferedReader br=new BufferedReader(isr);   
			String  str=null;
			while((str=br.readLine())!=null) {  //把从客户端传来的信息赋给str
				System.out.println(str);  //输出信息
			}
			socket.shutdownInput();  //关闭socket
                            is.close();
                            isr.close();
                            br.close();
                         } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {	
		}
	}
}

安卓上的代码:


客户端的主要功能是把主函数传来的字符串传给服务器

package activitytest.example.com.testchat;
import android.util.Log;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
   static String str=null;
   public Client(String str){this.str=str;}                 //设置构造方法,把主活动传来的字符串初始化为客户端的字符串
   static Scanner scanner=null;
   public static void send() {
      try {
         Log.i("Client","start conncet");     //判断是否运行到这
         Socket socket =new Socket("192.168.0.0",9998); //定义socket对象,传入ip地址,和端口,端口尽量定义在1024以上
         OutputStream os=socket.getOutputStream();     //得到outputStream对象
         PrintWriter pw=new PrintWriter(os);          //转换成字符流
         pw.write(str);                              //把字符串传给服务器
         pw.flush();                                
         socket.shutdownInput();                    //关闭相应的资源
         os.close();
         pw.close();
         socket.close();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      
   }
}

主活动代码:

设置了三个组件,分别是button用来发送,TextView用来显示发出的文本,EditView用来编辑文本

特别注意:安卓新的版本不允许在UI线程里执行复杂度高的程序,因此需要重开一个线程来执行,因此用了一个匿名线程类。

 
package activitytest.example.com.testchat;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    private Button b;
    private TextView t;
    public  static String s;
    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b=(Button)findViewById(R.id.send);
        t=(TextView)findViewById(R.id.textview);
        editText=(EditText)findViewById(R.id.edittext);
        b.setOnClickListener(new View.OnClickListener(){  //设置点击按钮
            public void onClick(View v){
               s=editText.getText().toString(); //获取editText的文本
                new Thread(new Runnable() {   //新的线程来执行客户端
                    @Override
                    public void run() {    //运行run方法
                        Client c=   new Client(s); //新建客户端对象
                        c.send();   //调用send方法
                    }
                }).start();   //开始线程
            }
        });
    }
}


layout代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="hello world"/>
    <EditText
        android:id="@+id/edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="welcome"/>
    <Button
        android:id="@+id/send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SEND"/>
</LinearLayout>




猜你喜欢

转载自blog.csdn.net/qq_30092289/article/details/80293123