Socket简单应用

来源:互联网 发布:网络调度表 编辑:程序博客网 时间:2024/06/02 14:41

一、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;  // 客户端socketDataOutputStream data_output=null;  // 客户端发送数据DataInputStream data_input=null;  // 客户端接收数据@Overrideprotected 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);}@Overridepublic 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;}@Overridepublic 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 exceptione.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;// 服务socketstatic 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 stubtry {// 创建套接字,并监听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 blocke.printStackTrace();}}}} catch (Exception e) {// TODO: handle exceptione.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
原创粉丝点击