Socket简单应用

一、Android手机端——Client(客户端)

main.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"
    tools:context=".MainActivity" >
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    <Button
        android:id="@+id/shundown"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="关闭电脑" />

    <Button
        android:id="@+id/restart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/button1"
        android:text="重启电脑" />

    <Button
        android:id="@+id/logoff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/button2"
        android:text="注销登录" />

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


        
        
    </LinearLayout>

</RelativeLayout>


MainActivity.class

package com.example.androidclient_activity;

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

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView.FindListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
	private Button shutdown,restart,logoff;
	private TextView text;
	Socket client_socket;  // 客户端socket
	DataOutputStream data_output=null;  // 客户端发送数据
	DataInputStream data_input=null;  // 客户端接收数据
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		shutdown=(Button) findViewById(R.id.shundown);
		restart=(Button) findViewById(R.id.restart);
		logoff=(Button) findViewById(R.id.logoff);
		text=(TextView) findViewById(R.id.textview);
		shutdown.setOnClickListener(this);
		restart.setOnClickListener(this);
		logoff.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO 自动生成的方法存根
		try { 
                 // 连接服务器
			client_socket=new Socket("192.168.21.1",4444);
			data_input=new DataInputStream(client_socket.getInputStream());
			data_output=new DataOutputStream(client_socket.getOutputStream());
		} catch (UnknownHostException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		String text="";
		switch (v.getId()) {
		case R.id.shundown:
			text = "shutdown";
			break;
		case R.id.restart:
			text = "restart";
			break;
		case R.id.logoff:
			text="logoff";
			break;
		default:
			break;
		}
		try {
			if ((data_output != null) && (!text.equals(""))) {
				data_output.writeUTF(text);
			}
			data_output.close();
			client_socket.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

}

二、重新建立一个java项目,实现服务器端

Pc_service.class

package pc_service;

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

import org.omg.CORBA.PUBLIC_MEMBER;

public class Pc_service {

	static ServerSocket serversocket = null;// 服务socket
	static DataInputStream data_input = null;// 输入流
	static DataOutputStream data_output = null;// 输出流

	/**
	 * @param args
	 */
	//   1: 创建服务器端套接字并绑定到一个端口上(0-1023是系统预留的,最好大于1024)
	//   2: 套接字设置监听模式等待连接请求
	//   3: 接受连接请求后进行通信
	//   4: 返回,等待赢一个连接请求
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			// 创建套接字,并监听
			serversocket = new ServerSocket(3333);
			System.out.println("listening 3333 port");

			while (true) {
				// 获取客户端套接字
				Socket client_socket = serversocket.accept();
				String send_msg = "";
				try {

					// 获取输入流,读取客户端传来的数据
					data_input = new DataInputStream(client_socket
							.getInputStream());
					String msg = data_input.readUTF();
					System.out.println(msg);
					// 判断输入,进行相应的操作
					data_output = new DataOutputStream(client_socket
							.getOutputStream());
					if (msg.equals("shutdown")) {
						//Shutdown();
						System.out.print(msg);
						// 发送消息回Android端
						send_msg = "shutdown ,60 seconds later ";
					} else if (msg.equals("restart")) {
						// Restart();
						 System.out.print(msg);
						send_msg = "restart ,60 seconds later ";
					} else if (msg.equals("logoff")) {
						//Logoff();
						 System.out.print(msg);
						send_msg = "logoff ,60 seconds later ";
					}
				} catch (Exception e) {
					// TODO: handle exception
				} finally {
					try {
						if (data_output != null) {
							data_output.writeUTF(send_msg);
							data_output.close();
						}
						data_input.close();
						// 关闭连接
						client_socket.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}

	// 用java.lang.Runtime类的exec方法,
	// Runtime r = Runtime.getRuntime();
	// r.exec("shutdown -s"); //shutdown是windows的关机程序,它的参数为
	// -i 显示 GUI 界面,必须是第一个选项
	// -l 注销(不能与选项 -m 一起使用)
	// -s 关闭此计算机
	// -r 关闭并重启动此计算机
	// -a 放弃系统关机
	// -m
	// computername 远程计算机关机/重启动/放弃
	// -t xx 设置关闭的超时为 xx 秒
	// -c "comment" 关闭注释(最大 127 个字符)
	// -f 强制运行的应用程序关闭而没有警告
	// -d [p]:xx:yy 关闭原因代码
	// u 是用户代码
	// p 是一个计划的关闭代码
	// xx 是一个主要原因代码(小于 256 的正整数)

	// 关机
	private static void Shutdown() throws IOException {
		Process p = Runtime.getRuntime().exec("shutdown -s -t 60");
		System.out.println("shutdown ,60 seconds later ");
	}

	// 重启
	private static void Restart() throws IOException {
		Process p = Runtime.getRuntime().exec("shutdown -r -t 60");
		System.out.println("restart ,60 seconds later ");
	}

	// 注销
	private static void Logoff() throws IOException {
		Process p = Runtime.getRuntime().exec("shutdown -l -t 60");
		System.out.println("logoff,60 seconds later ");
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值