java实现qq聊天室功能

时间:2022-12-26 10:08:44

一下是服务器端源码,供大家参考

下面是main.java

package com;

public class Main {

public static void main(String args[]) {
new ServerListener().start();

}
}
下面是ServerListener,java

package com;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JOptionPane;

public class ServerListener extends Thread {

int count;
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
System.out.println("监听是否有客户端连接");
try {
ServerSocket serverSocket = new ServerSocket(12345);
while (true) {
count++;
Socket socket = serverSocket.accept();
JOptionPane.showMessageDialog(null, "有客户端连接当前服务器");

// 一旦有客户端连接到服务器,开一个独立的线程
ChatThread chat = new ChatThread(socket, count);
chat.start();
ManagerChatThread.getInstance().add(chat);

}

} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

}
}
下面是ChatThread.java

package com;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

public class ChatThread extends Thread {

int count;

Socket socket;

StringBuffer sb;

public ChatThread(Socket socket, int count) {
// TODO Auto-generated constructor stub
this.socket = socket;
this.count = count;
}

/**
* 向客户端发送消息
*
* @param msg
*/
public void out(String msg) {
try {
socket.getOutputStream().write((msg+"\n").getBytes("utf-8"));

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Override
public void run() {
// TODO Auto-generated method stub
super.run();

// 读客户端的内容
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(
socket.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("客户端说"+count+":" + line);
// 向客户端发送信息
ManagerChatThread.getInstance().out(this, line);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



}
}

下面是ManagerChatThread.java
package com;

import java.util.ArrayList;

/**
* @author Administrator 管理客户端线程对象
*/
public class ManagerChatThread {
private ArrayList<ChatThread> al = new ArrayList<ChatThread>();

public static ManagerChatThread instance = new ManagerChatThread();

private ManagerChatThread() {
};

public static ManagerChatThread getInstance() {
return instance;
}

public void add(ChatThread chat){
al.add(chat);
}

//向客户端发送信息
public void out(ChatThread chat, String line){
for (int i = 0; i < al.size(); i++) {
if(!al.get(i).equals(chat))
{
al.get(i).out(line);
}
}
}
}
以上就是整个服务器端的代码了,支持多个客户端连接,服务器端循环接收来自客户端的请求


下满贴上Android客户端的代码

package com.exp.client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

public class Android_ClientActivity extends Activity implements OnClickListener {
EditText et;
TextView tv;
Socket socket;

BufferedWriter bw;
BufferedReader br;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);

tv = (TextView) findViewById(R.id.textView1);
et = (EditText) findViewById(R.id.editText1);
et.setText("");
tv.setText("");
}

@Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
// TODO Auto-generated method stub
new AsyncTask<String, String, Void>() {

@Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try {
socket = new Socket(params[0], 12345);

bw = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream(), "utf-8"));

// 读服务器消息
br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));

publishProgress("@sucess");
String my = null;
while ((my = br.readLine()) != null) {
publishProgress(my);
}

} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

@Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
if(values[0].equals("@sucess")){
tv.append("ok\n");
return;
}
tv.append("别人说:" + values[0]+"\n");
}

}.execute("10.0.2.2");
} else if (v.getId() == R.id.button2) {
// 将EidtText中的内容发送给服务器
String msg = et.getText().toString() + "\n";
try {
bw.write(msg);
bw.flush();

tv.append("自己说:" + msg);
et.setText("");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
}

简单的布局就不贴了,上面是android客户端的实现比java更简单,也可用纯java来实现

下面贴上java客户端的实现,以供大家参考

两个不同包的Test类

package exp;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);

try {
Socket socket = new Socket("192.168.0.112", 6000);

while(true){

//阻塞方法,等待键盘输入
String value = scanner.next();

OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
BufferedWriter bw = new BufferedWriter(osw);
bw.write(value+"\n");
bw.flush();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

}

package com;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;public class Test {	/**	 * @param args	 */	public static void main(String[] args) {		// TODO Auto-generated method stub				try {			Socket socket = new Socket("192.168.0.112", 5000);						//客户端向服务器发送数据			OutputStream os = socket.getOutputStream();			String value = "abcabc";			//字符串转化为字节数组			byte c[] = value.getBytes();			os.write(c);						//客户端接受服务器数据			InputStream is = socket.getInputStream();			byte b[] = new byte[1024];			int len = is.read(b);			String s = new String(b, 0, len);			System.out.println(s);					} catch (UnknownHostException e) {			// TODO Auto-generated catch block			e.printStackTrace();		} catch (IOException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}			}}


以上有注释以供大家参考,多学习,共勉