當前位置:首頁 » 操作系統 » 聊天伺服器源碼

聊天伺服器源碼

發布時間: 2022-04-22 05:24:52

⑴ 求聊天室聊天的伺服器端的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();
}
}

熱點內容
編程第一天 發布:2024-11-17 06:22:28 瀏覽:596
安卓媒體存儲器 發布:2024-11-17 06:22:26 瀏覽:12
怎麼做windows伺服器集群 發布:2024-11-17 06:19:59 瀏覽:693
php的ide 發布:2024-11-17 06:19:56 瀏覽:397
如何啟用安卓鍵盤 發布:2024-11-17 06:19:14 瀏覽:513
電腦電池怎麼配置 發布:2024-11-17 06:17:47 瀏覽:9
編程的男 發布:2024-11-17 06:07:43 瀏覽:514
工銀電子密碼器有什麼用 發布:2024-11-17 06:07:43 瀏覽:298
安卓tim快傳文件存儲在哪裡 發布:2024-11-17 05:54:03 瀏覽:613
pythonwindows後台運行 發布:2024-11-17 05:54:02 瀏覽:273