`

【转】 基于Socket通信的聊天室

 
阅读更多

原文地址:http://blog.csdn.net/xiaoxujie2007_/article/details/7720265

服务器端 ChatServer.java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Iterator;

public class ChatServer {
 
 private HashSet<Socket>clients=new HashSet<Socket>();//用于存储客户端用户列表
 
 public ChatServer()
 {
  try
  {
   ServerSocket ss=new ServerSocket(6666);
   while(true)
   {
    Socket socket=ss.accept();
    clients.add(socket);
    System.out.println("有一个用户进入聊天室...");
    new ServerThread(socket,clients).start();
   }
   
  }catch(Exception ex)
  {
   ex.printStackTrace();
  }
 }
 
 public static void main(String[]args)
 {
  new ChatServer();
  System.out.println("服务器已启动...");
 }
 
 
 class ServerThread extends Thread
 {
  private Socket s;
  private HashSet clients;
  
  public ServerThread(Socket s,HashSet clients)
  {
   this.s=s;
   this.clients=clients;
  }
  
  public void run()
  {
   try
   {
    BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
    while(true)
    {
     Iterator iter=clients.iterator();
     while(iter.hasNext())
     {
      String temp=br.readLine();
      Socket tempSocket=(Socket)iter.next();
      PrintWriter pt=new PrintWriter(tempSocket.getOutputStream());
      pt.println(new String(("from server:"+temp).getBytes(),"utf-8"));
      pt.flush();
      
//      尝试使用以下几种写法
      
//      OutputStreamWriter osw=new OutputStreamWriter(s.getOutputStream());
//      osw.write(br.readLine());
//      osw.flush();
      
//      OutputStream os=s.getOutputStream();
//      os.write(br.readLine().getBytes());
//      os.flush();
      
//      BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//      bw.write(br.readLine());
//      bw.flush();
      
//      BufferedOutputStream bos=new BufferedOutputStream(s.getOutputStream());
//      bos.write(br.readLine().getBytes());
//      bos.flush();
      
//      DataOutputStream dos=new DataOutputStream(s.getOutputStream());
//      dos.write(br.readLine().getBytes());
//      dos.flush();
      
     }
    }
   }catch(Exception ex)
   {
    ex.printStackTrace();
   }
  }
 }
}

 

 客户端程序是一个简单到不能再简单的安卓应用

   贴上main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
  android:id="@+id/tv_content"        
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

 ChatClientActivity.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ChatClientActivity extends Activity {
 /** Called when the activity is first created. */
 private TextView tv_content;
 private Button btn_send;
 private EditText et_content;
 Socket s ;
 String strContent="";
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  tv_content = (TextView) findViewById(R.id.tv_content);
  btn_send = (Button) findViewById(R.id.button1);
  et_content = (EditText) findViewById(R.id.editText1);
  try
  {
   s= new Socket("192.168.1.101", 6666);
  }catch(Exception ex)
  {
   ex.printStackTrace();
  }
  btn_send.setOnClickListener(
  new Button.OnClickListener() {
   public void onClick(View v) {
    try {
     String content = et_content.getText().toString();
     PrintWriter pw=new PrintWriter(s.getOutputStream());
     pw.println(content);
     pw.flush();
    } catch (Exception ex) {
     ex.printStackTrace();
    }
   }
  }
  );
  new Thread()
  {
   public void run()
   {
    while(true)
    {
     try {
      InputStreamReader isr=new InputStreamReader(s.getInputStream());
      BufferedReader br=new BufferedReader(isr);
      strContent+=br.readLine()+"\n";
      sendMsg(1,getContentHandler);
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
   }
  }.start();
 }
 
 public void sendMsg(int flag,Handler handler)
 {
  Message msg=new Message();
  msg.what=flag;
  handler.sendMessage(msg);
 }
 private final Handler getContentHandler = new Handler()
 {
  @Override
  public void handleMessage(Message msg)
  {
   switch (msg.what)
   {
    case 1:
     tv_content.setText(strContent);
     break;
   }
   super.handleMessage(msg);
  }
 };
}

 最后,不要忘记在AndroidManifest.xml中加入 :

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

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
  android:id="@+id/tv_content"        
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics