聊天服务器源码
⑴ 求聊天室聊天的服务器端的java源代码
import java.net.*;
import java.io.*;
import java.util.*;
public class ChatServer{
public static void main(String[] args)throws Exception{
ServerSocket svSocket =null;
//Vector threads 为ServerThread集合
Vector threads = new Vector();
//开始监听
System.out.println ("listening...");
try {
//创建服务端套接口
svSocket = new ServerSocket(5555);
}catch (Exception ex) {
System.out.println ("Server create ServerSocket failed!");
return;
}
try{
int nid = 0;
//监听是否有客户端连接
while(true){
Socket socket = svSocket.accept();
System.out.println ("accept a client");
//创建一个新的ServerThread
ServerThread st = new ServerThread(socket,threads);
//为客户端分配一个ID号
st.setID(nid++);
threads.add(st);
new Thread(st).start();
//向所有人广播有新客户端连接
for(int i=0;i < threads.size();i++){
ServerThread temp = (ServerThread)threads.elementAt(i);
//st.write("<#>Welcome "+ temp.getID()+" to enter the chatroom");
}
System.out.println ("Listen again...");
}
}catch(Exception ex){
System.out.println ("server is down");
}
}
}
/**
* 监听线程,监听是否有客户端发消息过来
*/
class ServerThread implements Runnable{
private Vector threads;
private Socket socket = null;
private DataInputStream in = null;
private DataOutputStream out = null;
private int nid;
//构造器
public ServerThread(Socket socket,Vector threads){
this.socket = socket;
this.threads = threads;
try {
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
}
catch (Exception ex) {
}
}
//实现run方法
public void run(){
System.out.println ("Thread is running");
try{
//监听客户端是否发消息过来
while(true){
String receive = in.readUTF();
if(receive == null)
return;
//当某客户离开,给其它客户端发消息
if(receive.equals("leave")){
for(int i=0;i < threads.size();i++){
ServerThread st = (ServerThread)threads.elementAt(i);
st.write("***"+getID()+"leaving...***");
}
}else{
//把某客户端发过来的发送到所有客户端
for(int i=0;i < threads.size();i++){
ServerThread st = (ServerThread)threads.elementAt(i);
st.write("<"+getID()+">: "+receive);
}
}
}
}catch(Exception ex){
//从Vector中删除该线程,表示该线程已经离开聊天室
threads.removeElement(this);
//ex.printStackTrace();
}
try{
socket.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
/**
* 服务端向客户端发送信息
*/
public void write(String msg){
synchronized(out){
try{
out.writeUTF(msg);
}catch(Exception ex){
}
}
}
/**
* 获得线程ID号
*/
public int getID(){
return this.nid;
}
/**
* 设置线程ID号
*/
public void setID(int nid){
this.nid = nid;
}
}
⑵ 易语言写聊天软件源码
制作聊天软件,需要有一个聊天服务器支持。除非只是点对点(就是只有双方使用)来发送。
我以前写过网吧的销售程序。功能也类似聊天软件一样,不过也是点对点方式。
P.s:别采纳!
⑶ 直播App直播软件源码的服务器用途有哪些
服务器的具体用途如下:
1)留言服务器:主要用于留言推送,到用户推送室聊天留言,私人留言。
2)业务服务器:手机直播业务部分,朋友关系,直播管理,货币系统,礼品系统等。
3)视频服务器:视频直播、视频点播、转码、存储、视频点播等。
4)我的即时聊天:使用node.js服务来建立自己的部署聊天服务器。
5)视频流(流媒体服务器):建议使用第三方CDN打开要使用的账户。
⑷ 如何用python编写一个聊天室
一、课程介绍
1.简介
本次项目课是实现简单聊天室程序的服务器端和客户端。
2.知识点
服务器端涉及到asyncore、asynchat和socket这几个模块,客户端用到了telnetlib、wx、time和thread这几个模块。
3.所需环境
本次课中编写客户端需要用到wxPython,它是一个GUI工具包,请先使用下面的命令安装:
$ sudo apt-get install python-wxtools
密码为shiyanlou
4.项目效果截图
登录窗口
二、项目实战(服务器端)
1.服务器类
首先需要一个聊天服务器,这里继承asyncore的dispatcher类来实现,代码如下
class ChatServer(dispatcher):
"""
聊天服务器
"""
def __init__(self, port):
dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind(('', port))
self.listen(5)
self.users = {}
self.main_room = ChatRoom(self)
def handle_accept(self):
conn, addr = self.accept()
ChatSession(self, conn)
2.会话类
有了服务器类还需要能维护每个用户的连接会话,这里继承asynchat的async_chat类来实现,代码如下:
class ChatSession(async_chat):
"""
负责和单用户通信
"""
def __init__(self, server, sock):
async_chat.__init__(self, sock)
self.server = server
self.set_terminator('
')
self.data = []
self.name = None
self.enter(LoginRoom(server))
def enter(self, room):
'从当前房间移除自身,然后添加到指定房间'
try:
cur = self.room
except AttributeError:
pass
else:
cur.remove(self)
self.room = room
room.add(self)
def collect_incoming_data(self, data):
'接受客户端的数据'
self.data.append(data)
def found_terminator(self):
'当客户端的一条数据结束时的处理'
line = ''.join(self.data)
self.data = []
try:
self.room.handle(self, line)
except EndSession:
self.handle_close()
def handle_close(self):
async_chat.handle_close(self)
self.enter(LogoutRoom(self.server))
3.命令解释器
现在就需要一个命令解释器能够解释用户的命令,例如登录、查询在线用户和发消息等,代码如下:
class CommandHandler:
"""
命令处理类
"""
def unknown(self, session, cmd):
'响应未知命令'
session.push('Unknown command: %s
' % cmd)
def handle(self, session, line):
'命令处理'
if not line.strip():
return
parts = line.split(' ', 1)
cmd = parts[0]
try:
line = parts[1].strip()
except IndexError:
line = ''
meth = getattr(self, 'do_' + cmd, None)
try:
meth(session, line)
except TypeError:
self.unknown(session, cmd)
4.房间
接下来就需要实现聊天室的房间了,这里我们定义了三种房间,分别是用户刚登录时的房间、聊天的房间和退出登录的房间,这三种房间都有一个公共的父类,代码如下:
class Room(CommandHandler):
"""
包含多个用户的环境,负责基本的命令处理和广播
"""
def __init__(self, server):
self.server = server
self.sessions = []
def add(self, session):
'一个用户进入房间'
self.sessions.append(session)
def remove(self, session):
'一个用户离开房间'
self.sessions.remove(session)
def broadcast(self, line):
'向所有的用户发送指定消息'
for session in self.sessions:
session.push(line)
def do_logout(self, session, line):
'退出房间'
raise EndSession
class LoginRoom(Room):
"""
刚登录的用户的房间
"""
def add(self, session):
'用户连接成功的回应'
Room.add(self, session)
session.push('Connect Success')
def do_login(self, session, line):
'登录命令处理'
name = line.strip()
if not name:
session.push('UserName Empty')
elif name in self.server.users:
session.push('UserName Exist')
else:
session.name = name
session.enter(self.server.main_room)
class ChatRoom(Room):
"""
聊天用的房间
"""
def add(self, session):
'广播新用户进入'
session.push('Login Success')
self.broadcast(session.name + ' has entered the room.
')
self.server.users[session.name] = session
Room.add(self, session)
def remove(self, session):
'广播用户离开'
Room.remove(self, session)
self.broadcast(session.name + ' has left the room.
')
def do_say(self, session, line):
'客户端发送消息'
self.broadcast(session.name + ': ' + line + '
')
def do_look(self, session, line):
'查看在线用户'
session.push('Online Users:
')
for other in self.sessions:
session.push(other.name + '
')
class LogoutRoom(Room):
"""
用户退出时的房间
"""
def add(self, session):
'从服务器中移除'
try:
del self.server.users[session.name]
except KeyError:
pass
5.服务器端完整代码
#!/usr/bin/python
# encoding: utf-8
from asyncore import dispatcher
from asynchat import async_chat
import socket, asyncore
PORT = 6666 #端口
class EndSession(Exception):
"""
自定义会话结束时的异常
"""
pass
class CommandHandler:
"""
命令处理类
"""
def unknown(self, session, cmd):
'响应未知命令'
session.push('Unknown command: %s
' % cmd)
def handle(self, session, line):
'命令处理'
if not line.strip():
return
parts = line.split(' ', 1)
cmd = parts[0]
try:
line = parts[1].strip()
except IndexError:
line = ''
meth = getattr(self, 'do_' + cmd, None)
try:
meth(session, line)
except TypeError:
self.unknown(session, cmd)
class Room(CommandHandler):
"""
包含多个用户的环境,负责基本的命令处理和广播
"""
def __init__(self, server):
self.server = server
self.sessions = []
def add(self, session):
'一个用户进入房间'
self.sessions.append(session)
def remove(self, session):
'一个用户离开房间'
self.sessions.remove(session)
def broadcast(self, line):
'向所有的用户发送指定消息'
for session in self.sessions:
session.push(line)
def do_logout(self, session, line):
'退出房间'
raise EndSession
class LoginRoom(Room):
"""
刚登录的用户的房间
"""
def add(self, session):
'用户连接成功的回应'
Room.add(self, session)
session.push('Connect Success')
def do_login(self, session, line):
'登录命令处理'
name = line.strip()
if not name:
session.push('UserName Empty')
elif name in self.server.users:
session.push('UserName Exist')
else:
session.name = name
session.enter(self.server.main_room)
class ChatRoom(Room):
"""
聊天用的房间
"""
def add(self, session):
'广播新用户进入'
session.push('Login Success')
self.broadcast(session.name + ' has entered the room.
')
self.server.users[session.name] = session
Room.add(self, session)
def remove(self, session):
'广播用户离开'
Room.remove(self, session)
self.broadcast(session.name + ' has left the room.
')
def do_say(self, session, line):
'客户端发送消息'
self.broadcast(session.name + ': ' + line + '
')
def do_look(self, session, line):
'查看在线用户'
session.push('Online Users:
')
for other in self.sessions:
session.push(other.name + '
')
class LogoutRoom(Room):
"""
用户退出时的房间
"""
def add(self, session):
'从服务器中移除'
try:
del self.server.users[session.name]
except KeyError:
pass
class ChatSession(async_chat):
"""
负责和单用户通信
"""
def __init__(self, server, sock):
async_chat.__init__(self, sock)
self.server = server
self.set_terminator('
')
self.data = []
self.name = None
self.enter(LoginRoom(server))
def enter(self, room):
'从当前房间移除自身,然后添加到指定房间'
try:
cur = self.room
except AttributeError:
pass
else:
cur.remove(self)
self.room = room
room.add(self)
def collect_incoming_data(self, data):
'接受客户端的数据'
self.data.append(data)
def found_terminator(self):
'当客户端的一条数据结束时的处理'
line = ''.join(self.data)
self.data = []
try:
self.room.handle(self, line)
except EndSession:
self.handle_close()
def handle_close(self):
async_chat.handle_close(self)
self.enter(LogoutRoom(self.server))
class ChatServer(dispatcher):
"""
聊天服务器
"""
def __init__(self, port):
dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind(('', port))
self.listen(5)
self.users = {}
self.main_room = ChatRoom(self)
def handle_accept(self):
conn, addr = self.accept()
ChatSession(self, conn)
if __name__ == '__main__':
s = ChatServer(PORT)
try:
asyncore.loop()
except KeyboardInterrupt:
print
三、项目实战(客户端)
完成了服务器端后,就需要实现客户端了,这里客户端连接服务器使用了telnetlib模块。
1.登录窗口
这里的图形界面包选择了wxPython,前面有安装说明,登录窗口通过继承wx.Frame类来实现,代码如下:
class LoginFrame(wx.Frame):
"""
登录窗口
⑸ 提供一个由Java编写的包括服务器端和客户端的聊天工具的原代码
//聊天室的客户端
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
public class ChatClient extends Applet{
protected boolean loggedIn;//登入状态
protected Frame cp;//聊天室框架
protected static int PORTNUM=7777; //缺省端口号7777
protected int port;//实际端口号
protected Socket sock;
protected BufferedReader is;//用于从sock读取数据的BufferedReader
protected PrintWriter pw;//用于向sock写入数据的PrintWriter
protected TextField tf;//用于输入的TextField
protected TextArea ta;//用于显示对话的TextArea
protected Button lib;//登入按钮
protected Button lob;//登出的按钮
final static String TITLE ="Chatroom applet>>>>>>>>>>>>>>>>>>>>>>>>";
protected String paintMessage;//发表的消息
public ChatParameter Chat;
public void init(){
paintMessage="正在生成聊天窗口";
repaint();
cp=new Frame(TITLE);
cp.setLayout(new BorderLayout());
String portNum=getParameter("port");//呢个参数勿太明
port=PORTNUM;
if (portNum!=null) //书上是portNum==null,十分有问题
port=Integer.parseInt(portNum);
//CGI
ta=new TextArea(14,80);
ta.setEditable(false);//read only attribute
ta.setFont(new Font("Monospaced",Font.PLAIN,11));
cp.add(BorderLayout.NORTH,ta);
Panel p=new Panel();
Button b;
//for login button
p.add(lib=new Button("Login"));
lib.setEnabled(true);
lib.requestFocus();
lib.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
login();
lib.setEnabled(false);
lob.setEnabled(true);
tf.requestFocus();//将键盘输入锁定再右边的文本框中
}
});
//for logout button
p.add(lob=new Button ("Logout"));
lob.setEnabled(false);
lob.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
logout();
lib.setEnabled(true);
lob.setEnabled(false);
lib.requestFocus();
}
});
p.add(new Label ("输入消息:"));
tf=new TextField(40);
tf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(loggedIn){
//pw.println(Chat.CMD_BCAST+tf.getText());//Chat.CMD....是咩野来?
int j=tf.getText().indexOf(":");
if(j>0) pw.println(Chat.CMD_MESG+tf.getText());
else
pw.println(Chat.CMD_BCAST+tf.getText());
tf.setText("");//勿使用flush()?
}
}
});
p.add(tf);
cp.add(BorderLayout.SOUTH,p);
cp.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
//如果执行了setVisible或者dispose,关闭窗口
ChatClient.this.cp.setVisible(false);
ChatClient.this.cp.dispose();
logout();
}
});
cp.pack();//勿明白有咩用?
//将Frame cp放在中间
Dimension us=cp.getSize(),
them=Toolkit.getDefaultToolkit().getScreenSize();
int newX=(them.width-us.width)/2;
int newY=(them.height-us.height)/2;
cp.setLocation(newX,newY);
cp.setVisible(true);
paintMessage="Window should now be visible";
repaint();
}
//登录聊天室
public void login(){
if(loggedIn) return;
try{
sock=new Socket(getCodeBase().getHost(),port);
is=new BufferedReader(new InputStreamReader(sock.getInputStream()));
pw=new PrintWriter(sock.getOutputStream(),true);
}catch(IOException e){
showStatus("Can't get socket: "+e);
cp.add(new Label("Can't get socket: "+e));
return;}
//构造并且启动读入器,从服务器读取数据,输出到文本框中
//这里,长成一个线程来避免锁住资源(lockups)
new Thread (new Runnable(){
public void run(){
String line;
try{
while(loggedIn &&((line=is.readLine())!=null))
ta.appendText(line+"\n");
}catch(IOException e){
showStatus("我的天啊,掉线了也!!!!");
return;
}
}
}).start();
//假定登录(其实只是打印相关信息,并没有真正登录)
// pw.println(Chat.CMD_LOGIN+"AppletUser");
pw.println(Chat.CMD_LOGIN+"AppletUser");
loggedIn =true;
}
//模仿退出的代码
public void logout(){
if(!loggedIn)
return;
loggedIn=false;
try{
if(sock!=null)
sock.close();
}catch(IOException ign){
// 异常处理哦
}
}
//没有设置stop的方法,即使从浏览器跳到另外一个网页的时候
//聊天程序还可以继续运行
public void paint(Graphics g){
Dimension d=getSize();
int h=d.height;
int w=d.width;
g.fillRect(0,0,w,2);
g.setColor(Color.black);
g.drawString(paintMessage,10,(h/2)-5);
}
}
聊天室服务器端
import java.net.*;
import java.io.*;
import java.util.*;
public class ChatServer{
//聊天室管理员ID
protected final static String CHATMASTER_ID="ChatMaster";
//系统信息的分隔符
protected final static String SEP=": ";
//服务器的Socket
protected ServerSocket servSock;
//当前客户端列表
protected ArrayList clients;
//调试标记
protected boolean DEBUG=false;
public ChatParameter Chat;
//主方法构造一个ChatServer,没有返回值
public static void main(String[] argv){
System.out.println("Chat server0.1 starting>>>>>>>>>>>>>>>>");
ChatServer w=new ChatServer();
w.runServer();
System.out.println("***ERROR*** Chat server0.1 quitting");
}
//构造和运行一个聊天服务
ChatServer(){
Chat=new ChatParameter();
clients=new ArrayList();
try{
servSock=new ServerSocket(7777);//实有问题拉,不过可能是他自己定义既一个class.
System.out.println("Chat Server0.1 listening on port:"+7777);
}catch(Exception e){
log("IO Exception in ChatServer.<init>");
System.exit(0);
}
}
public void runServer(){
try{
while(true){
Socket us=servSock.accept();
String hostName=us.getInetAddress().getHostName();
System.out.println("Accpeted from "+hostName);
//一个处理的线程
ChatHandler cl=new ChatHandler(us,hostName);
synchronized(clients){
clients.add(cl);
cl.start();
if(clients.size()==1)
cl.send(CHATMASTER_ID,"Welcome!You are the first one here");
else{
cl.send(CHATMASTER_ID,"Welcome!You are the latest of"+
clients.size()+" users.");
}
}
}
}catch(Exception e){
log("IO Exception in runServer:"+e);
System.exit(0);
}
}
protected void log(String s){
System.out.println(s);
}
//处理会话的内部的类
protected class ChatHandler extends Thread {
//客户端scoket
protected Socket clientSock;
//读取socket的BufferedReader
protected BufferedReader is ;
//在socket 上发送信息行的PrintWriter
protected PrintWriter pw;
//客户端出主机
protected String clientIP;
//句柄
protected String login;
public ChatHandler (Socket sock,String clnt)throws IOException {
clientSock=sock;
clientIP=clnt;
is=new BufferedReader(
new InputStreamReader(sock.getInputStream()));
pw=new PrintWriter (sock.getOutputStream(),true);
}
//每一个ChatHandler是一个线程,下面的是他的run()方法
//用于处理会话
public void run(){
String line;
try{
while((line=is.readLine())!=null){
char c=line.charAt(0);//我顶你老母啊 ,果只Chat.CMD咩xx冇定义 扑啊///!!!
line=line.substring(1);
switch(c){
//case Chat.CMD_LOGIN:
case 'l':
if(!Chat.isValidLoginName(line)){
send(CHATMASTER_ID,"LOGIN"+line+"invalid");
log("LOGIN INVALID from:"+clientIP);
continue;
}
login=line;
broadcast(CHATMASTER_ID,login+" joins us,for a total of"+
clients.size()+" users");
break;
// case Chat.CMD_MESG:
case 'm':
if(login==null){
send(CHATMASTER_ID,"please login first");
continue;
}
int where =line.indexOf(Chat.SEPARATOR);
String recip=line.substring(0,where);
String mesg=line.substring (where+1);
log("MESG: "+login+"--->"+recip+": "+mesg);
ChatHandler cl=lookup(recip);
if(cl==null)
psend(CHATMASTER_ID,recip+"not logged in.");
else
cl.psend(login,mesg);
break;
//case Chat.CMD_QUIT:
case 'q':
broadcast(CHATMASTER_ID,"Goodbye to "+login+"@"+clientIP);
close();
return;//ChatHandler结束
// case Chat.CMD_BCAST:
case 'b':
if(login!=null)
broadcast(login,line);
else
log("B<L FROM"+clientIP);
break;
default:
log("Unknow cmd"+c+"from"+login+"@"+clientIP);
}
}
}catch(IOException e){
log("IO Exception :"+e);
}finally{
//sock 结束,我们完成了
//还不能发送再见的消息
//得有简单的基于命令的协议才行
System.out.println(login+SEP+"All Done");
synchronized(clients){
clients.remove(this);
if(clients.size()==0){
System.out.println(CHATMASTER_ID+SEP+
"I'm so lonely I could cry>>>>>");
}else if(clients.size()==1){
ChatHandler last=(ChatHandler)clients.get(0);
last.send(CHATMASTER_ID,"Hey,you are talking to yourself again");
}
else{
broadcast(CHATMASTER_ID,"There are now"+clients.size()+" users");
}
}
}
}
protected void close(){
if(clientSock==null){
log("close when not open");
return;
}
try{
clientSock.close();
clientSock=null;
}catch(IOException e){
log("Failure ring close to "+clientIP);
}
}
//发送一条消息给用户
public void send(String sender,String mesg){
pw.println(sender+SEP+"*>"+mesg);
}
//发送私有的消息
protected void psend(String sender ,String msg){
send("<*"+sender+"*>",msg);
}
//发送一条消息给所有的用户
public void broadcast (String sender,String mesg){
System.out.println("Broadcasting"+sender+SEP+mesg);
for(int i=0;i<clients.size();i++){
ChatHandler sib=(ChatHandler)clients.get(i);
if(DEBUG)
System.out.println("Sending to"+sib);
sib.send(sender,mesg);
}
if(DEBUG) System.out.println("Done broadcast");
}
protected ChatHandler lookup(String nick){
synchronized(clients){
for(int i=0;i<clients.size();i++){
ChatHandler cl=(ChatHandler)clients.get(i);
if(cl.login.equals(nick))
return cl;
}
}
return null;
}
//将ChatHandler对象转换成一个字符串
public String toString(){
return "ChatHandler["+login+"]";
}
}
}
public class ChatParameter {
public static final char CMD_BCAST='b';
public static final char CMD_LOGIN='l';
public static final char CMD_MESG='m';
public static final char CMD_QUIT='q';
public static final char SEPARATOR=':';//?????
public static final int PORTNUM=7777;
public boolean isValidLoginName(String line){
if (line.equals("CHATMASTER_ID"))
return false;
return true;
}
public void main(String[] argv){
}
}
由于界面原因 所以比较乱 全部复制出去 重新整理一下就行了/
⑹ JAVA 聊天室服务器端和客户端完整代码
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.util.*;
import java.io.*;
public class Server extends JFrame
{
JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("文件");
JMenu m2 = new JMenu("帮助");
JMenuItem mi1 = new JMenuItem("连接");
JMenuItem mi2 = new JMenuItem("退出");
JLabel lab1 = new JLabel("用户在线列表");
JLabel lab2 = new JLabel("消息:");
JTextArea ta = new JTextArea(9,30);
java.awt.List list = new java.awt.List(9);
JTextField tf = new JTextField(24);
JButton b = new JButton("发送");
JScrollPane sp = new JScrollPane();
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
ServerSocket serverSocket;
Socket socket;
ArrayList array = new ArrayList();
int connect;
public Server()
{
super("聊天服务器");
setJMenuBar(mb);
mb.add(m1);
mb.add(m2);
m1.add(mi1);
m1.addSeparator();
m1.add(mi2);
sp.getViewport().add(ta);
p1.setLayout(new BorderLayout());
p3.add(lab1);
p1.add(p3,BorderLayout.NORTH);
p1.add(list,BorderLayout.SOUTH);
p2.add(lab2);
p2.add(tf);
p2.add(b);
getContentPane().add(sp,BorderLayout.NORTH);
getContentPane().add(p1,BorderLayout.CENTER);
getContentPane().add(p2,BorderLayout.SOUTH);
pack();
//服务器端界面居中显示
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = this.getSize();
if(frameSize.width > screenSize.width)
{
frameSize.width = screenSize.width;
}
if(frameSize.height > screenSize.height)
{
frameSize.height = screenSize.height;
}
setLocation((screenSize.width - frameSize.width)/2,
(screenSize.height - frameSize.height)/2);
setSize(400,430);
setVisible(true);
setResizable(false);
mi1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(serverSocket == null)
{
try
{
serverSocket = new ServerSocket(7000);
ta.append("系统提示:"+" 聊天服务器"
+" 正在启动......\n");
}
catch(IOException ex)
{
ta.append("系统提示:"+" 聊天服务器"
+" 启动失败!\n");
}
}
else
{
ta.append("系统消息:"+" 聊天服务器"
+" 已经启动......\n");
}
//启动监听客户端连接线程
Thread t = new Watch();
t.start();
}
});
mi2.addActionListener(new ServerListener());
b.addActionListener(new ServerListener());
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
closeAll();
System.exit(0);
}
});
}
class Watch extends Thread
{
public void run()
{
while(true)
{
if(array.size() <= 10)
{
try
{
socket = serverSocket.accept();
}
catch(IOException ex)
{
ta.append("系统消息: "+ex+"\n");
}
//创建客户端线程,一个线程对应一个客户端
Client c = new Client(socket);
array.add(c);
c.start();
}
else
{
ta.append("系统消息:"+" 聊天服务器"
+" 已经超过最大连接数,请待会连接!\n");
}
}
}
}
class Client extends Thread
{
String name;
String ip;
String ipAddress;
Socket socket;
BufferedReader br;
PrintStream ps;
public Client(Socket s)
{
try
{
socket = s;
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
ps = new PrintStream(s.getOutputStream());
}
catch (IOException ex)
{
ta.append("系统消息: "+ex+"\n");
}
}
public void run()
{
String info;
try
{
while(true)
{
info = br.readLine();
if(info == null)
break;
StringTokenizer st = new StringTokenizer(info, ":");
String keyword = st.nextToken();
//处理客户端传来的信息
if (keyword.equals("CONNECT"))
{
name = st.nextToken();
ip = st.nextToken();
ipAddress = ip.substring(ip.indexOf("/")+1);
ta.append("系统消息: " + name + "/"
+ ipAddress +" 已经连接\n");
list.add(name + " " + ip
+" 已经登录");
notifyChatRoom();
}
else if (keyword.equals("MSG"))
{
String broadcast = st.nextToken();
StringBuffer message = new StringBuffer("MSG:" +broadcast);
message.append(st.nextToken("\0"));
if (broadcast.equals("BROAD"))
{
⑺ 一套完整的视频直播聊天室源码怎么开发
视频直播聊天室源码怎么开发?首先,我们将其分为五部分:采集、编码,传输, 服务器处理,解码,渲染。
1、采集:采集就是我们平时“开摄像头录像”的部分,用户通过摄像头将视频传递到网络上,这里是比较简单的一部分,只是适配起来会比较麻烦,毕竟手机种类众多,但本身的技术要求和其他模块比起来还是简单很多的。
2、前处理:前处理阶段是视频直播聊天室源码在将视频传输到服务器之前要做好的处理工作,包括美颜算法、视频模糊、添加水印等,都在这一环节做成
3、编码:为什么要将视频进行编码呢?因为原音视频文件是很大的,会占用很大的带宽,只有在编码完成后,视频文件才会变得小一些,这样会更节省带宽。
难点在于:分辨率,帧率,码率,GOP等参数的平衡,视频直播聊天室源码如何使音视频文件又小又清晰,这是个问题
4、传输:将主播端文件传输给服务器
5、服务器处理:在服务器完成对文件的检测(包括鉴黄等)后,将文件通过CDN发送到观众的手机端。
6、解码和渲染:交给用户自己的手机吧。
这是一个视频直播聊天室源码的工作步骤,我们需要回避很多坑才能做好视频直播聊天室源码的开发,如有需要帮助的地方,可以追问我。
⑻ 求LIUNX 下 类似聊天室服务器源码 JAVA 或C 能在linux用就可以 接受客户端联接
1、聊天室的原理就是服务端建立socket监听,客户端建立socket客户端与服务端socket交互,服务端通过广播或单通道的方式将处理后的数据下发
2、服务端需要建立socket服务,采用何种技术不重要,java/c/.net这些都可以
3、客户端需要实现socket客户端,采用何种技术也不重要,java/c/.net这些都可以
4、服务端与客户端的交互报文协议和交互流程需要事先约定好
5、具体实现举例,给你提供个思路:
a. 服务端使用java编写,编译后启动,启动后就是实现一个socket的服务端,网上很多类似代码,在linux下安装一个jre就可以了
b.服务端采用C实现socket服务端,可以考虑使用ACE框架来简化开发,linux下g++编译很方便,编译后直接运行,前提是ACE等相关工具和环境需要配置好
c.服务端构建一个J2EE的web应用,然后在linux下部署在tomcat下,启动部分与方法a一致
6、其实很简单,关键是了解聊天室的原理其实就是一个套接字通讯,与具体的技术或编程工具无关
⑼ 速求用JAVA语言写聊天室的源代码
【ClientSocketDemo.java 客户端Java源代码】
import java.net.*;
import java.io.*;
public class ClientSocketDemo
{
//声明客户端Socket对象socket
Socket socket = null;
//声明客户器端数据输入输出流
DataInputStream in;
DataOutputStream out;
//声明字符串数组对象response,用于存储从服务器接收到的信息
String response[];
//执行过程中,没有参数时的构造方法,本地服务器在本地,取默认端口10745
public ClientSocketDemo()
{
try
{
//创建客户端socket,服务器地址取本地,端口号为10745
socket = new Socket("localhost",10745);
//创建客户端数据输入输出流,用于对服务器端发送或接收数据
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//获取客户端地址及端口号
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
//向服务器发送数据
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
//从服务器接收数据
response = new String[3];
for (int i = 0; i < response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//执行过程中,有一个参数时的构造方法,参数指定服务器地址,取默认端口10745
public ClientSocketDemo(String hostname)
{
try
{
//创建客户端socket,hostname参数指定服务器地址,端口号为10745
socket = new Socket(hostname,10745);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; i < response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//执行过程中,有两个个参数时的构造方法,第一个参数hostname指定服务器地址
//第一个参数serverPort指定服务器端口号
public ClientSocketDemo(String hostname,String serverPort)
{
try
{
socket = new Socket(hostname,Integer.parseInt(serverPort));
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; i < response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
String comd[] = args;
if(comd.length == 0)
{
System.out.println("Use localhost(127.0.0.1) and default port");
ClientSocketDemo demo = new ClientSocketDemo();
}
else if(comd.length == 1)
{
System.out.println("Use default port");
ClientSocketDemo demo = new ClientSocketDemo(args[0]);
}
else if(comd.length == 2)
{
System.out.println("Hostname and port are named by user");
ClientSocketDemo demo = new ClientSocketDemo(args[0],args[1]);
}
else System.out.println("ERROR");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
【ServerSocketDemo.java 服务器端Java源代码】
import java.net.*;
import java.io.*;
public class ServerSocketDemo
{
//声明ServerSocket类对象
ServerSocket serverSocket;
//声明并初始化服务器端监听端口号常量
public static final int PORT = 10745;
//声明服务器端数据输入输出流
DataInputStream in;
DataOutputStream out;
//声明InetAddress类对象ip,用于获取服务器地址及端口号等信息
InetAddress ip = null;
//声明字符串数组对象request,用于存储从客户端发送来的信息
String request[];
public ServerSocketDemo()
{
request = new String[3]; //初始化字符串数组
try
{
//获取本地服务器地址信息
ip = InetAddress.getLocalHost();
//以PORT为服务端口号,创建serverSocket对象以监听该端口上的连接
serverSocket = new ServerSocket(PORT);
//创建Socket类的对象socket,用于保存连接到服务器的客户端socket对象
Socket socket = serverSocket.accept();
System.out.println("This is server:"+String.valueOf(ip)+PORT);
//创建服务器端数据输入输出流,用于对客户端接收或发送数据
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//接收客户端发送来的数据信息,并显示
request[0] = in.readUTF();
request[1] = in.readUTF();
request[2] = in.readUTF();
System.out.println("Received messages form client is:");
System.out.println(request[0]);
System.out.println(request[1]);
System.out.println(request[2]);
//向客户端发送数据
out.writeUTF("Hello client!");
out.writeUTF("Your ip is:"+request[1]);
out.writeUTF("Your port is:"+request[2]);
}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
ServerSocketDemo demo = new ServerSocketDemo();
}
}