【转】 基于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>

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
基于socket通信的多人聊天室可以通过以下步骤实现: 1. 创建一个服务器端程序,使用特定的端口监听客户端的连接请求。可以使用Python中的socket库来实现。 2. 在服务器端程序中,使用socket库的bind()方法将服务器端的IP地址和端口号绑定到一个socket对象上,并使用listen()方法开始监听客户端连接请求。 3. 在服务器端程序中,使用accept()方法来接收客户端的连接请求,并获得一个与客户端通信socket对象。 4. 为每个客户端连接创建一个新的线程,以便能够同时处理多个客户端的消息。 5. 在服务器端程序中,使用recv()方法接收客户端发送的消息,并将消息广播给所有已连接的客户端。这样所有客户端之间就可以实现即时的多人聊天。 6. 在服务器端程序中,使用send()方法将服务器端接收到的消息发送给所有已连接的客户端。 7. 在客户端程序中,使用socket库的connect()方法连接到服务器端的IP地址和端口号。 8. 在客户端程序中,使用send()方法将客户端发送的消息发送给服务器端。 9. 在客户端程序中,使用recv()方法接收服务器端发送的消息,并将其显示在客户端的窗口上。 需要注意的是,由于socket通信是基于TCP协议的,因此可以实现可靠的数据传输,但是在实现聊天室时,需要处理客户端进程退出的情况,并及时清理相关资源,避免程序异常或资源泄漏等问题的出现。 以上是基于socket通信的多人聊天室的简要实现步骤,具体实现过程还需要根据编程语言和具体的需求进行进一步的开发和调试。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值