android局域网聊天+服务器

//终端java服务器

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;

//超级终端
public class Socket_Server extends ServerSocket implements Runnable {
    private static final int SERVER_PORT = 10000;
    static Vector<Socket> v;
    PrintWriter out2;
    static int StaticNum;// 记录用户数目

    public Socket_Server() throws IOException {
        super(SERVER_PORT);

        Thread send = new Thread(new Runnable() {
            public void run() {
                BufferedReader msg = new BufferedReader(new InputStreamReader(
                        System.in));
                String line;
                while (true) {

                    try {
                        line = msg.readLine();
                        try {
                            if (line.equalsIgnoreCase("checkclient")) {
                                if (v.isEmpty()) {
                                    System.out.println("目前没有客户连接");
                                    continue;
                                }
                                for (int i = 0; i < v.size();) {
                                    System.out.println(v.get(i)
                                            .getRemoteSocketAddress());
                                    i++;
                                }
                                continue;
                            }// 查看客户端连接情况
                            if (line.equalsIgnoreCase("?")
                                    || line.equalsIgnoreCase("help")) {
                                System.out.println("checkclient 查看客户端信息");
                                continue;
                            }// 显示帮助信息
                            out2 = new PrintWriter(v.get(
                                    Integer.valueOf((line.substring(0,
                                            line.indexOf("-")))) - 1)
                                    .getOutputStream(), true);
                            // "1-msg"代表发给1号客户端msg
                            out2.println("服务器:"
                                    + line.substring(line.indexOf("-") + 1,
                                            line.length()));

                        } catch (StringIndexOutOfBoundsException e) {
                            System.out.println("请按照以下格式回复");
                            System.out.println("客户端编号-回复内容");
                        } catch (NumberFormatException e) {
                            System.out.println("请按照以下格式回复");
                            System.out.println("客户端编号-回复内容");
                        } catch (Exception e) {
                            System.out.println("客户端未连接");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }

        });
        send.start();
        try {
            while (true) {
                Socket socket = accept();
                StaticNum++;
                new CreateServerThread(socket);
                v.add(socket);// 新客户端添加进入Vector
            }
        } catch (IOException e) {
        } finally {
            close();
        }
    }

    // --- CreateServerThread
    class CreateServerThread extends Thread {
        private Socket client;
        private BufferedReader in;
        private PrintWriter out;
        int num = StaticNum;

        public CreateServerThread(Socket s) throws IOException {

            client = s;

            in = new BufferedReader(new InputStreamReader(
                    client.getInputStream(), "UTF-8"));
            out = new PrintWriter(client.getOutputStream(), true);
            // out.println("--- Welcome ---");
            // out.println("-成功连接至服务器-");
            out.println("您是" + num + "号客户端");
            System.out.println("新客户端已连接。。。");
            System.out.println(s.getRemoteSocketAddress());
            start();

        }

        public void run() {
            try {
                String line = in.readLine();

                while (!line.equals("bye")) {
                    System.out.println(num + "号客户端:" + line);
                    // out.println("发送给服务器的消息:" + line);
                    // out.println(line);
                    try {// 支持局域网用户互相发送信息
                        out2 = new PrintWriter(v.get(
                                Integer.valueOf((line.substring(0,
                                        line.indexOf("-")))) - 1)
                                .getOutputStream(), true);
                        out2.println("来自"
                                + client.getRemoteSocketAddress()
                                + "的消息:"
                                + line.substring(line.indexOf("-") + 1,
                                        line.length()));
                        out.println("发送给"
                                + v.get(Integer.valueOf((line.substring(0,
                                        line.indexOf("-")))) - 1)
                                        .getRemoteSocketAddress()
                                + "的消息:"
                                + line.substring(line.indexOf("-") + 1,
                                        line.length()));
                    } catch (Exception e) {
                    }

                    line = in.readLine();
                }
                out.println("--- See you, bye! ---");
                System.out.println("客户端正常断开连接");
                client.close();
            } catch (Exception e) {
                System.out.println("客户端异常断开连接");
                try {
                    client.close();
                } catch (IOException e1) {
                    System.out.println("客户端关闭异常");
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        System.out.println("启动服务器。。。");
        v = new Vector<Socket>();
        StaticNum = 0;
        new Socket_Server();

    }

    @Override
    public void run() {
    }

}



//android客户端代码

package com.example.android2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;
import android.widget.TextView;

@SuppressLint("HandlerLeak")
public class MainActivity extends Activity {
    private TextView myTextView;
    private TextView ViewMsg;
    BufferedReader in;
    PrintWriter out;
    private ImageButton Ibtn;
    String msg;
    static Socket socket;
    Handler h = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        try {
            socket = new Socket("192.168.0.17", 10000);

            // in = new BufferedReader(new InputStreamReader(
            // socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myTextView = (TextView) findViewById(R.id.editText1);
        ViewMsg = (TextView) findViewById(R.id.editText2);
        ViewMsg.setText("已连接服务器...");
        Ibtn = (ImageButton) findViewById(R.id.imageButton1);
        Ibtn.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                // 用户当前为按下
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    // 用户当前为抬起
                    String send = String.valueOf(myTextView.getText());
                    ViewMsg.setText(ViewMsg.getText() + send);
                    out.println(send);
                    myTextView.setText("");
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                }
                return false;
            }
        });
        new Thread() {
            public void run() {
                try {
                    in = new BufferedReader(new InputStreamReader(
                            socket.getInputStream(), "UTF-8"));
                } catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                try {
                    msg = in.readLine();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                while (true) {
                    try {
                        msg = in.readLine();
                        Log.d("d", msg);
                        if (!msg.equalsIgnoreCase("bye")) {
                            Message m = new Message();
                            MainActivity.this.h.sendMessage(m);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        h = new Handler() {
            public void handleMessage(Message m) {
                ViewMsg.setText(ViewMsg.getText() + msg);
            }
        };
    }

    @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;
    }

}

//activity_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" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="48dp"
        android:ems="10" />

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editText1"
        android:layout_toRightOf="@+id/editText1"
        android:src="@drawable/ic_launcher" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/imageButton1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/imageButton1"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="16dp"
        android:ems="10" />

</RelativeLayout>

 

 

//android2 Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.android2.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

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

</manifest>

posted on 2014-04-28 23:36  carlzcs  阅读(452)  评论(0)    收藏  举报

导航