安卓Socket和ServerSocket的使用

使用安卓Socket完成以下需求:

       当服务器端接收到用户发来的信息后,将在前面加上标头Android:,并将信息发送回安卓端

->>定义服务端程序:

本程序将在10001端口上等待连接,之后分别取得客户端输入输出流对象,并将接收的客户端信息发送给服务端,以上程序运行之后自动进入阻塞状态,并等待客户端进行连接,本次客户端通过Android完成。

package com.example.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	
	private ServerSocket serverSocket;
	private boolean started = false;
	
	public static void main(String[] args){
		System.out.println("服务器启动...");
//		new Server().start(8321);
		
		try {
			ServerSocket serverSockets = new ServerSocket(10001);
			//监听10001端口
			Socket socket = serverSockets.accept();//接收客户端请求
			
			PrintStream pStream = new PrintStream(socket.getOutputStream());//取得客户端输出流
			//字符缓冲区读取
			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			StringBuffer infoStr = new StringBuffer();
			infoStr.append("Android:");//回应数据
			infoStr.append(reader.readLine());//接收数据
			pStream.print(infoStr);//发送消息
			
			pStream.close();
			reader.close();
			serverSockets.close();
			socket.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}

->>客户端程序:

package com.example.allexceptedemo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Enumeration;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

	private EditText contentInfo;  
	private String msg = "";  
	private Socket socket;  
	private TextView showInfo;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		showInfo = (TextView)findViewById(R.id.showInfo);
		contentInfo = (EditText)findViewById(R.id.contentInfo);
		
	}
	
	/**
	 * 按钮事件处理
	 * @param v
	 */
	public void mainClick(View v)
	{
		switch (v.getId()) {
		case R.id.send:
			try {
					Socket socketClient = new Socket("192.168.1.110",10001);
					PrintStream pStream = new PrintStream(socketClient.getOutputStream());
					//缓冲区读取
					BufferedReader buffReader = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
					//发送数据
					pStream.println(contentInfo.getText().toString());
					//设置文本
					showInfo.setText(buffReader.readLine());
					//清空输入栏
					contentInfo.setText(null);
					
					pStream.close();
					buffReader.close();
					socketClient.close();
				
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			break;
//
		default:
			break;
		}
	}
	
}

XML布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" 
    android:padding="2dip"
    >
    
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/showInfo"
        />

    <EditText
        android:layout_width="220dip"
        android:layout_height="wrap_content"
        android:id="@+id/contentInfo"
        android:layout_marginTop="120dip"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="mainClick"
        android:id="@+id/send"
        android:layout_marginTop="120dip"
        android:text="@string/send"
        android:layout_marginLeft="220dip"
        />

</RelativeLayout>


 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值