利用socket套接字实现简易聊天室,下面是简易的安卓客户端和电脑实现交互,

实现界面:

客户端:

wKiom1XnssajFVylAACaL8R_gmo660.jpg




服务器端:

wKioL1XntOnggkXMAABjtsirvWE442.jpg








代码如下




服务器端MySocketServer.Java:(服务器端新建一个javaProject)

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


public class MySocketServer {

    public static void main(String[] args)throws IOException{
        
        ServerSocket serversocket=new ServerSocket(30000);
        
        System.out.println("=======连接成功========");
        while(true){
            
            final Socket socket=serversocket.accept();
            Thread t=new Thread(new Runnable(){

                public void run() {
                    // TODO Auto-generated method stub
                    try {
                        InputStream input=socket.getInputStream();
                        OutputStream output=socket.getOutputStream();
                        BufferedReader buff=new BufferedReader(new InputStreamReader(input));
                        output.write("服务器:小朋友,你好呀!".getBytes("UTF-8"));
                        output.flush();
                        socket.shutdownOutput();
                        String line="";
                        while((line=buff.readLine())!=null){
                            System.out.println(line);
                        }
                        output.close();
                        input.close();
                        buff.close();
                        socket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }            
                    
                }
                
            });
            t.start();
        }
    }
}






客户端 :(安卓project)




1.MainActivity代码

package com.example.mysocket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    private EditText edit1,edit2;
    private TextView text3;
    private Button button;
    String name="",message="",buffer="";
    Handler handler=new Handler(){
        public void handleMessage(Message msg){
            if(msg.what==0x101){
                Bundle bundle=msg.getData();
                text3.append(""+bundle.getString("msg")+"\n");
                
            }
        }
        
    };
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edit1=(EditText)findViewById(R.id.edit1);
        edit2=(EditText)findViewById(R.id.edit2);
        text3=(TextView)findViewById(R.id.text3);
        text3.setMovementMethod(ScrollingMovementMethod.getInstance());
        button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                name=edit1.getText().toString();
                message=edit2.getText().toString();
                text3.append("我:"+message+"\n");
                new Thread(new Mythread()).start();
                
            }
        });
    }

    class Mythread implements Runnable{
        public void run(){
            Message m=new Message();
            m.what=0x101;
            Bundle bundle=new Bundle();
            Socket socket =new Socket();
            try {
                socket.connect(new InetSocketAddress("10.248.25.146", 30000), 10000);
                OutputStream os=socket.getOutputStream();
                os.write((name+":"+message).getBytes("UTF-8"));
                BufferedReader buff=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String line=null;
                buffer="";
                while((line=buff.readLine())!=null){
                    buffer=buffer+line;
                }
                os.flush();
                bundle.putString("msg", buffer.toString());
                m.setData(bundle);
                handler.sendMessage(m);
                buff.close();
                os.close();
                socket.close();
                
            } catch(SocketTimeoutException e){
                bundle.putString("msg","连接超时!" );
                m.setData(bundle);
                handler.sendMessage(m);
            }catch (IOException ee) {
                // TODO Auto-generated catch block
                ee.printStackTrace();
            }
            
        }
    }
}

2.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" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="你的名字:"/>

    <EditText
        android:id="@+id/edit1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button"
        android:layout_toRightOf="@+id/text1" />

    <EditText
        android:id="@+id/edit2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/edit1"
        android:layout_below="@+id/edit1"
        android:layout_toRightOf="@+id/text1" />

    <Button
        android:id="@+id/button"
        android:layout_below="@+id/edit2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="send"/>

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/edit2"
        android:layout_alignBottom="@+id/edit2"
        android:layout_alignParentLeft="true"
        android:text="信息:" />
    <TextView
        android:id="@+id/text3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button"
        android:scrollbars="vertical"/>

</RelativeLayout>




这样就能实现啦!

(ps1:只能在同一局域网内聊天,可以修改ip获取方式打破这一局限!)

(ps2:可以修改服务器端实现多人在线聊天!)