㈠ java中怎樣實現網上聊天對話功能
如果採用HTTP協議,也就是網頁傳輸那種方式很簡單,同過內嵌對象象application,session為核心的JSP編程,即可實現。但基於TCP/IP通訊方式,無論是在JAVAEE還是在安卓系統,這種開發出來的聊天通訊更快,更實用。
㈡ java 編程題網路聊天室
Public
class
Client
___extends_____
Thread
//定義一個Client線程類
{
Private
____Socket____
m_socket;//定義一個socket對象;
Public
Client()//默認構造函數
{
}
Public
boolean
ConnToServer(String
strip,int
port)//連接指定IP和埠的伺服器,如果連接成功,返回true,否則返回false。
{
_m_socket=new
ServerSocket(strip,port)______________________
____return
(m_socket==null)________________________
}
Class
SendData
____extends_____
Thread
{
Socket
m_sendso;
BufferReader
in;
Outprintstream
out;
Public
SendData(Socket
so)
{
___________________
Start();
}
Public
void
run(
)
{
_____in=new
BufferedReader(new
InputStreamReader(System.in)_____________
//不斷從鍵盤獲取字元串發送給伺服器
}
}
Class
RecvData
___extends______
Thread
{
Socket
m_recvso;
BufferReader
in;
Outprintstream
out;
Public
RecvData
(Socket
so)
{
___________________
Start();
}
已經填了幾個空了。。。有些不太會。。。但是填了的一定正確的。。。。
其他你自己搞定吧。。。
㈢ Java網路聊天室
你自己調試編譯下,四個java文件:
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import java.io.*;
import java.util.Hashtable;public class ChatArea extends Panel implements ActionListener,Runnable
{
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread threadMessage=null;
TextArea 談話顯示區,私聊顯示區=null;
TextField 送出信息=null;
Button 確定,刷新談話區,刷新私聊區;
Label 提示條=null;
String name=null;
Hashtable listTable;
List listComponent=null;
Choice privateChatList;
int width,height;
public ChatArea(String name,Hashtable listTable,int width,int height)
{
setLayout(null);
setBackground(Color.orange);
this.width=width;
this.height=height;
setSize(width,height);
this.listTable=listTable;
this.name=name;
threadMessage=new Thread(this);
談話顯示區=new TextArea(10,10);
私聊顯示區=new TextArea(10,10);
確定=new Button("送出信息到:");
刷新談話區=new Button("刷新談話區");
刷新私聊區=new Button("刷新私聊區");
提示條=new Label("雙擊聊天者可私聊",Label.CENTER);
送出信息=new TextField(28);
確定.addActionListener(this);
送出信息.addActionListener(this);
刷新談話區.addActionListener(this);
刷新私聊區.addActionListener(this);
listComponent=new List();
listComponent.addActionListener(this);
privateChatList=new Choice();
privateChatList.add("大家(*)");
privateChatList.select(0);
add(談話顯示區);
談話顯示區.setBounds(10,10,(width-120)/2,(height-120));
add(私聊顯示區);
私聊顯示區.setBounds(10+(width-120)/2,10,(width-120)/2,(height-120));
add(listComponent);
listComponent.setBounds(10+(width-120),10,100,(height-160));
add(提示條);
提示條.setBounds(10+(width-120),10+(height-160),110,40);
Panel pSouth=new Panel();
pSouth.add(送出信息);
pSouth.add(確定);
pSouth.add(privateChatList);
pSouth.add(刷新談話區);
pSouth.add(刷新私聊區);
add(pSouth);
pSouth.setBounds(10,20+(height-120),width-20,60);
}
public void setName(String s)
{
name=s;
}
public void setSocketConnection(Socket socket,DataInputStream in,DataOutputStream out)
{
this.socket=socket;
this.in=in;
this.out=out;
try
{
threadMessage.start();
}
catch(Exception e)
{
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==確定||e.getSource()==送出信息)
{
String message="";
String people=privateChatList.getSelectedItem();
people=people.substring(0,people.indexOf("("));
message=送出信息.getText();
if(message.length()>0)
{
try {
if(people.equals("大家"))
{
out.writeUTF("公共聊天內容:"+name+"說:"+message);
}
else
{
out.writeUTF("私人聊天內容:"+name+"悄悄地說:"+message+"#"+people);
}
}
catch(IOException event)
{
}
}
}
else if(e.getSource()==listComponent)
{
privateChatList.insert(listComponent.getSelectedItem(),0);
privateChatList.repaint();
}
else if(e.getSource()==刷新談話區)
{
談話顯示區.setText(null);
}
else if(e.getSource()==刷新私聊區)
{
私聊顯示區.setText(null);
}
}
public void run()
{
while(true)
{
String s=null;
try
{
s=in.readUTF();
if(s.startsWith("聊天內容:"))
{
String content=s.substring(s.indexOf(":")+1);
談話顯示區.append("\n"+content);
}
if(s.startsWith("私人聊天內容:"))
{
String content=s.substring(s.indexOf(":")+1);
私聊顯示區.append("\n"+content);
}
else if(s.startsWith("聊天者:"))
{
String people=s.substring(s.indexOf(":")+1,s.indexOf("性別"));
String sex=s.substring(s.indexOf("性別")+2);
listTable.put(people,people+"("+sex+")");
listComponent.add((String)listTable.get(people));
listComponent.repaint();
}
else if(s.startsWith("用戶離線:"))
{
String awayPeopleName=s.substring(s.indexOf(":")+1);
listComponent.remove((String)listTable.get(awayPeopleName));
listComponent.repaint();
談話顯示區.append("\n"+(String)listTable.get(awayPeopleName)+"離線");
listTable.remove(awayPeopleName);
}
Thread.sleep(5);
}
catch(IOException e)
{
listComponent.removeAll();
listComponent.repaint();
listTable.clear();
談話顯示區.setText("和伺服器的連接已中斷\n必須刷新瀏覽器才能再次聊天");
break;
}
catch(InterruptedException e)
{
}
}
}
}
========================內容過多,未完……
㈣ java 如何實現簡單的網路聊天功能,給點思路嘛謝謝,想寫寫,但是完全沒有思路
網路聊天,比如A跟B聊天,首先A和B都必須連接到公用的伺服器,然後伺服器根據消息的接受者來講消息轉發給對應的人。比如A給B發消息,A首先將消息發送個伺服器,伺服器接收到該消息,然後看到是A給B發的消息,然後將消息轉發給B。A和B不能直接通信,而是用伺服器周轉。所以你需要實現一個服務端,一個客戶端,然後服務端可以同時與多個客戶端建立連接,然後服務端實現消息的轉發。
㈤ 用JAVA 編寫簡單網路聊天程序
/**
* 基於UDP協議的聊天程序
*
* 2007.9.18
* */
//導入包
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;
public class Chat extends JFrame implements ActionListener
{
//廣播地址或者對方的地址
public static final String sendIP = "172.18.8.255";
//發送埠9527
public static final int sendPort = 9527;
JPanel p = new JPanel();
List lst = new List(); //消息顯示
JTextField txtIP = new JTextField(18); //填寫IP地址
JTextField txtMSG = new JTextField(20); //填寫發送消息
JLabel lblIP = new JLabel("IP地址:");
JLabel lblMSG = new JLabel("消息:");
JButton btnSend = new JButton("發送");
byte [] buf;
//定義DatagramSocket的對象必須進行異常處理
//發送和接收數據報包的套接字
DatagramSocket ds = null;
//=============構造函數=====================
public Chat()
{
CreateInterFace();
//注冊消息框監聽器
txtMSG.addActionListener(this);
btnSend.addActionListener(this);
try
{
//埠:9527
ds =new DatagramSocket(sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
//============接受消息============
//匿名類
new Thread(new Runnable()
{
public void run()
{
byte buf[] = new byte[1024];
//表示接受數據報包
while(true)
{
try
{
DatagramPacket dp = new DatagramPacket(buf,1024,InetAddress.getByName(txtIP.getText()),sendPort);
ds.receive(dp);
lst.add("【消息來自】◆" + dp.getAddress().getHostAddress() + "◆"+"【說】:" + new String (buf,0,dp.getLength()) /*+ dp.getPort()*/,0);
}
catch(Exception e)
{
if(ds.isClosed())
{
e.printStackTrace();
}
}
}
}
}).start();
//關閉窗體事件
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.out.println("test");
int n=JOptionPane.showConfirmDialog(null,"是否要退出?","退出",JOptionPane.YES_NO_OPTION);
if(n==JOptionPane.YES_OPTION)
{
dispose();
System.exit(0);
ds.close();//關閉ds對象//關閉數據報套接字
}
}
});
}
//界面設計布局
public void CreateInterFace()
{
this.add(lst,BorderLayout.CENTER);
this.add(p,BorderLayout.SOUTH);
p.add(lblIP);
p.add(txtIP);
p.add(lblMSG);
p.add(txtMSG);
p.add(btnSend);
txtIP.setText(sendIP);
//背景顏色
lst.setBackground(Color.yellow);
//JAVA默認風格
this.setUndecorated(true);
this.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
this.setSize(600,500);
this.setTitle("〓聊天室〓");
this.setResizable(false);//不能改變窗體大小
this.setLocationRelativeTo(null);//窗體居中
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(true);
txtMSG.requestFocus();//消息框得到焦點
}
//===============================Main函數===============================
public static void main(String[]args)
{
new Chat();
}
//================================發送消息===============================
//消息框回車發送消息事件
public void actionPerformed(ActionEvent e)
{
//得到文本內容
buf = txtMSG.getText().getBytes();
//判斷消息框是否為空
if (txtMSG.getText().length()==0)
{
JOptionPane.showMessageDialog(null,"發送消息不能為空","提示",JOptionPane.WARNING_MESSAGE);
}
else{
try
{
InetAddress address = InetAddress.getByName(sendIP);
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
ds.send(dp);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
txtMSG.setText("");//清空消息框
//點發送按鈕發送消息事件
if(e.getSource()==btnSend)
{
buf = txtMSG.getText().getBytes();
try
{
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
txtMSG.setText("");//清空消息框
txtMSG.requestFocus();
}
}
}
㈥ 怎麼用java做區域網的聊天工具(聊天室)
呵呵,樓主您好!要用Java做聊天室說簡單也不簡單,但是說難呢也不難.
說簡單點,就是會話跟蹤技術(我個人這樣理解).要做聊天室,您需要
使用到的工具: tomcat 伺服器(因為是免費的,其他也可以哦,呵呵).
Myeclipse(sun公司提供的編寫Java程序的工具,別說你不知道哈,
哪樣的話我就暈倒了哦,呵呵)
頁面框架的設計:index.jsp(聊天室主頁面)index_top.jsp(聊天室的頂部頁面)
usersonline.jsp(在線人數的統計及顯示頁面) sendMessage.jsp(發送信息的頁面)
showMessage.jsp(顯示聊天信息的頁面)register.jsp(用戶注冊的頁面)
login.jsp(用戶登錄頁面)
當然,這是最簡單的設計方式咯.您也可以設計得更好點.
頁面介紹與功能:
index.jsp 主要是聊天室的主頁面.由上中下3個框架組成,中間部分在分為
左右2個框架.實際上index.jsp就是一個由於5個框架組成的頁面
頂部框架:放index_top.jsp頁面.可以設計自己聊天室的特色(比如說:logo)
中間部分的左邊框架:showMessage.jsp 顯示聊天的信息
中間部分的右邊框架:usersonline.jsp(在線人數的統計及顯示頁面)
底部框架:sendMessage.jsp 這個發送信息的jsp頁面.不多說吧
聊天室的框架的設計大楷就是這樣子咯
實現聊天:
1.編寫一個servlet,用戶處理的信息(包括驗證用戶是否登錄和聊天信息)。
2.用戶發送信息之後,將發送的信息存放到Application中(群聊)(放在session中就是私聊)
3.顯示信息的頁面每個XX秒中獲取session或者Application中的數據顯示出來就OK了
更多的東西還是需要您學習Ajax之後再做,會有不一樣的效果哦。祝您成功喲.呵呵
㈦ Java在線聊天的實現技術
socket套接字
㈧ 想用Java web實現在線聊天,求大神指點。
這個只有通過客戶端向伺服器主動請求的方式實現,因為http協議是無狀態的一次請求結束之後,伺服器就沒法再找到客戶端的瀏覽器了,所以只能是客戶端定期到伺服器查詢有無新消息。消息頁面的彈出可以使用js實現。打開多個相同頁面可能會同時都彈出吧,這個我不太清楚,不過一般很少有人會去開多個頁面吧。至於伺服器壓力的問題,我覺得應該不是什麼大問題,因為每次請求的數據量也不是很大,你可以將請求時間間隔設置的長一點。希望我的回答能對你有幫助。
㈨ 如何使用Java實現網站頁面在線聊天
那種timeout不斷去查詢這種方法,就將之前堵塞的線程解鎖,思路應該是下面這種。。,同時再次傳遞信息給伺服器,伺服器就會主動將信息推送給客戶端,所以讓線程堵塞,具體的我有代碼,onload事件激發自動傳送一個指令給伺服器,直到有客戶端向服...
㈩ 簡單網路聊天程序 java程序代碼
1.伺服器端的代碼:
//ChatServer.Java
import java.net.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChatServer extends JFrame {
JTextArea ta = new JTextArea();
ServerSocket server = null;
Collection cClient = new ArrayList();
public ChatServer(int port) throws Exception {
server = new ServerSocket(port);
add(ta, BorderLayout.CENTER);
setBounds(200, 200, 300, 450);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setVisible(true);
}
public void startServer() throws Exception {
while (true) {
Socket s = server.accept();
cClient.add(new ClientConn(s));
ta.append(s.getInetAddress().getHostName() + "進入" + " " + "埠號"
+ s.getPort());
ta.append("\n" + "當前在前總人數: " + cClient.size() + "\n\n");
}
}
class ClientConn extends Frame implements Runnable, ActionListener {
TextArea ta1 = null;
TextArea ta2 = null;
Button btn = null;
Socket s = null;
public ClientConn(Socket s) {
ta1 = new TextArea(3, 30);
ta2 = new TextArea(2, 15);
btn = new Button("發送");
this.setLayout(new BorderLayout());
this.add(ta1, BorderLayout.CENTER);
this.add(ta2, BorderLayout.SOUTH);
this.add(btn, BorderLayout.EAST);
this.setSize(300, 200);
this.setVisible(true);
this.setTitle("" + s.getInetAddress().getHostName() + "埠"
+ s.getPort());
this.s = s;
(new Thread(this)).start();
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
try {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("伺服器:\n" + ta2.getText() + "\n");
ta1.append("伺服器:\n" + ta2.getText() + "\n");
ta2.setText("");
} catch (IOException E) {
}
}
public void send(String str, String st) throws IOException {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(st + "說:\n" + str);
}
public void dispose() {
try {
super.dispose();
ta.append(s.getInetAddress().getHostName() + "退出" + "\n");
if (s != null)
s.close();
cClient.remove(this);
ta.append("當前在線人數: " + cClient.size() + "\n\n");
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
String st = s.getInetAddress().getHostName();
while (str != null && str.length() != 0) {
for (Iterator it = cClient.iterator(); it.hasNext();) {
ClientConn cc = (ClientConn) it.next();
if (this != cc) {
cc.send(str, st);
}
}
ta1.append(st + "說:\n" + str + "\n");
str = dis.readUTF();
}
this.dispose();
} catch (Exception e) {
this.dispose();
}
}
}
public static void main(String[] args) throws Exception {
JFrame.(true);
ChatServer cs = new ChatServer(8888);
cs.startServer();
}
}
2.客戶端的代碼:
//ChatClient.java
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChatClient extends JFrame {
JTextArea ta = new JTextArea("你可以通過此客戶端的聊天!" + "\n" );
TextArea tf = new TextArea(3, 21);
JButton btn = new JButton("發送");
JPanel jp = new JPanel();
Socket s = null;
public ChatClient() throws Exception {
this.setLayout(new BorderLayout(10, 10));
this.add(ta, BorderLayout.CENTER);
jp.add(btn, BorderLayout.SOUTH);
this.add(tf, BorderLayout.SOUTH);
this.add(jp, BorderLayout.EAST);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
String sSend = tf.getText();
if (sSend.trim().length() == 0)
return;
ChatClient.this.send(sSend);
tf.setText("");
ta.append("你說:" + "\n");
ta.append(sSend + "\n");
} catch (Exception e) {
e.printStackTrace();
}
}
});
btn.setMnemonic(KeyEvent.VK_ENTER);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setBounds(300, 300, 400, 500);
setVisible(true);
tf.requestFocus();
try {
s = new Socket("10.6.86.28", 8888);
} catch (Exception e) {
ta.append("對不起!無法連接伺服器" + "\n");
}
(new Thread(new ReceiveThread())).start();
}
public void send(String str) throws Exception {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
}
public void disconnect() throws Exception {
s.close();
}
public static void main(String[] args) throws Exception {
JFrame.(true);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ChatClient cc = new ChatClient();
String str = br.readLine();
while (str != null && str.length() != 0) {
cc.send(str);
str = br.readLine();
}
cc.disconnect();
}
class ReceiveThread implements Runnable {
public void run() {
if (s == null)
return;
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
while (str != null && str.length() != 0) {
ChatClient.this.ta.append(str + "\n");
str = dis.readUTF();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} }