導航:首頁 > 編程語言 > java網路編程聊天

java網路編程聊天

發布時間:2022-07-24 14:21:11

Ⅰ 淺談java中如何利用socket進行網路編程(一)

Socket是網路上運行的兩個程序間雙向通訊的一端,它既可以接受請求,也可以發送請求,利用它可以較為方便的編寫網路上的數據的傳遞。在java中,有專門的socket類來處理用戶的請求和響應。利用SOCKET類的方法,就可以實現兩台計算機之間的通訊。這里就介紹一下在JAVA中如何利用socket進行網路編程。 在Java中Socket可以理解為客戶端或者伺服器端的一個特殊的對象,這個對象有兩個關鍵的方法,一個是getInputStream方法,另一個是getOutputStream方法。getInputStream方法可以得到一個輸入流,客戶端的Socket對象上的getInputStream方法得到的輸入流其實就是從伺服器端發回的數據流。GetOutputStream方法得到一個輸出流,客戶端Socket對象上的getOutputStream方法返回的輸出流就是將要發送到伺服器端的數據流,(其實是一個緩沖區,暫時存儲將要發送過去的數據)。 程序可以對這些數據流根據需要進行進一步的封裝。本文的例子就對這些數據流進行了一定的封裝(關於封裝可以參考Java中流的實現部分)。 一、建立伺服器類 Java中有一個專門用來建立Socket伺服器的類,名叫ServerSocket,可以用伺服器需要使用的埠號作為參數來創建伺服器對象。ServerSocket server = new ServerSocket(9998) 這條語句創建了一個伺服器對象,這個伺服器使用9998號埠。當一個客戶端程序建立一個Socket連接,所連接的埠號為9998時,伺服器對象server便響應這個連接,並且server.accept()方法會創建一個Socket對象。伺服器端便可以利用這個Socket對象與客戶進行通訊。Socket incoming = server.accept() 進而得到輸入流和輸出流,並進行封裝BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter(incoming.getOutputStream(),true); 隨後,就可以使用in.readLine()方法得到客戶端的輸入,也可以使用out.println()方法向客戶端發送數據。從而可以根據程序的需要對客戶端的不同請求進行回應。

Ⅱ java網路編程問題

1.每個客戶端上線的時候都會把自己的IP傳給伺服器,伺服器會維護一個QQ號碼與對應IP的列表。
2.
A如果想給B發消息,首先要去伺服器上通過B的QQ號查詢B的IP,然後與B建立P2P的通信,不怎能是每次通訊都經過伺服器的,那樣伺服器的負載就太重了,肯定沒法即時響應。

Ⅲ 求一個用JAVA寫的網路編程的網路聊天系統,能夠實現兩個人聊天信息收發。

這個是客戶端
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class client extends Frame implements ActionListener{
int i=1;Frame f;
TextField ip,port;
Label Lip,Lport;
Button connect,exit;
public static void main(String args[])
{client c1 = new client();
c1.init();
}
public void init()
{
f=new Frame("client connection");
f.setLayout(new FlowLayout());
ip =new TextField("localhost");
port =new TextField("8189",5);
Lip=new Label("ip address");
Lport=new Label("port");
connect=new Button("connect");
exit=new Button("exit");
connect.addActionListener(this);
exit.addActionListener(this);
f.add(Lip);
f.add(ip);
f.add(Lport);
f.add(port);
f.add(connect);
f.add(exit);
f.setSize(500,60);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==exit)
System.exit(0);
if(e.getSource()==connect)
{
new Thread(new threadclient(ip.getText(),port.getText(),i)).start();
i++;
}
}
}
class threadclient extends Frame implements Runnable,ActionListener{
String ip,port;
int no;
Frame f;
TextArea ta;
TextArea name;
TextField tf;
Button send,bye;
InputStream ins;
Socket s;
PrintStream out1;
BufferedReader in;
BufferedWriter out;
threadclient(String n,String m,int i)
{
ip=n;
port=m;
no=i;
}
public void run(){
f=new Frame("client NO." +no);
f.setLayout(new FlowLayout());
ta=new TextArea("",10,30,TextArea.SCROLLBARS_BOTH);
tf=new TextField("",20);
send=new Button("send");
bye=new Button("bye");
send.addActionListener(this);
bye.addActionListener(this);
f.add(ta);
f.add(tf);
f.add(send);
f.add(bye);
f.setSize(300,300);
f.setVisible(true);
Integer tmp=new Integer(port);
int portint =tmp.intValue();
try
{
s=new Socket(ip,portint);
in=new BufferedReader(new InputStreamReader(s.getInputStream()));
out1=new PrintStream(s.getOutputStream());
ta.append(in.readLine()+"\n");
}catch(Exception e)
{
System.out.println(e.getMessage()+" ss");
}
}
public void send(String txt){
try{
out1.println(txt);
out1.flush();
ta.append(in.readLine()+"\n");
}catch(IOException e)
{
System.out.println(e.getMessage()+"send");
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==bye){
send("BYE");
System.exit(0);
}
if (e.getSource()==send)
send(tf.getText());
}
}

這個是伺服器
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class server {
private static Map<String,Socket> clientMap=new HashMap<String,Socket>();
public static void main(String[] args) {
int i = 1;
try {
ServerSocket s = new ServerSocket(8189);
for (;;) {
Socket incoming = s.accept();
System.out.println("連接成功" + i);
ThreadedEchoHandler teh=new ThreadedEchoHandler(incoming, i);
teh.start();
String name=teh.getClientname();
clientMap.put(name,incoming);
i++;
}
} catch (Exception e) {
System.out.println(e);
}
}
}
class ThreadedEchoHandler extends Thread {
Frame f;
TextArea ta;
TextField tf;
Button send, bye;
InputStream ins;
Socket s;
PrintStream out1;
BufferedReader in;
PrintWriter out;
public ThreadedEchoHandler(Socket i, int c) {
incoming = i;
counter = c;
f=new Frame("server");
f.setLayout(new FlowLayout());
ta=new TextArea("",10,30,TextArea.SCROLLBARS_BOTH);
tf=new TextField("",20);
send=new Button("send");
bye=new Button("bye");
send.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
send(tf.getText());

}

});
bye.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
send("bye");

}

});
f.add(ta);
f.add(tf);
f.add(send);
f.add(bye);
f.setSize(300,300);
f.setVisible(true);
}

public String getClientname() {
try {
in = new BufferedReader(new InputStreamReader(
incoming.getInputStream()));
out = new PrintWriter(incoming.getOutputStream(), true);
return in.readLine();
} catch (IOException e) {
System.out.println(e.getMessage()+"get");
}
return null;
}
public void send(String context){
out.println(context);
out.flush();
}
public void run() {
try {

boolean done = false;
while (!done) {
String str = in.readLine();

if (str == null)
done = true;
else {
out.println("Echo(" + counter + "):" + str);
ta.append("Echo(" + counter + "):" + str+"\n");
if (str.trim().equals("BYE"))
done = true;
}
}
incoming.close();
} catch (Exception e) {
System.out.println(e.getMessage()+"run");
}
}
private Socket incoming;
private int counter;
}

這個鳥東西是個新手寫的。唉,太爛了,我無力吐槽。

Ⅳ 我要一份用java網路編程寫的點對點的兩人聊天程序(TCP和UDP)

Server端:
import java.io.*;
import java.net.*;
import java.applet.Applet;
public class TalkServer{
public static void main(String args[]) {
try{
ServerSocket server=null;
try{
server=new ServerSocket(4700);
}catch(Exception e) {
System.out.println("can not listen to:"+e);
}
Socket socket=null;
try{
socket=server.accept();
}catch(Exception e) {
System.out.println("Error."+e);
}
String line;
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter os=new PrintWriter(socket.getOutputStream());
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Client:"+is.readLine());
line=sin.readLine();
while(!line.equals("bye")){
os.println(line);
os.flush();
System.out.println("Server:"+line);
System.out.println("Client:"+is.readLine());
line=sin.readLine();
}
os.close();
is.close();
socket.close();
server.close();
}catch(Exception e){
System.out.println("Error:"+e);
}
}
}

Client端:
import java.io.*;
import java.net.*;
public class TalkClient {
public static void main(String args[]) {
try{
Socket socket=new Socket("127.0.0.1",4700);
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
PrintWriter os=new PrintWriter(socket.getOutputStream());
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String readline;
readline=sin.readLine(); //從系統標准輸入讀入一字元串
while(!readline.equals("bye")){
os.println(readline);
os.flush();
System.out.println("Client:"+readline);
System.out.println("Server:"+is.readLine());
readline=sin.readLine(); //從系統標准輸入讀入一字元串
}
os.close(); //關閉Socket輸出流
is.close(); //關閉Socket輸入流
socket.close(); //關閉Socket
}catch(Exception e) {
System.out.println("Error"+e); //出錯,則列印出錯信息
}
}
}

Ⅳ 用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 web實現在線聊天,求大神指點。

這個只有通過客戶端向伺服器主動請求的方式實現,因為http協議是無狀態的一次請求結束之後,伺服器就沒法再找到客戶端的瀏覽器了,所以只能是客戶端定期到伺服器查詢有無新消息。消息頁面的彈出可以使用js實現。打開多個相同頁面可能會同時都彈出吧,這個我不太清楚,不過一般很少有人會去開多個頁面吧。至於伺服器壓力的問題,我覺得應該不是什麼大問題,因為每次請求的數據量也不是很大,你可以將請求時間間隔設置的長一點。希望我的回答能對你有幫助。

Ⅶ JAVA編區域網聊天室

我是用多播實現的,MulticastSocket是DatagramSocket的子類,暫時還只能用於區域網,不過多播是可以在廣域網上進行的

大概步驟如下:

1.加入多播組

2.發送/接收數據包

發送需要從文本輸入

接收時使用了一個線程循環接收

3.發生異常離開多播組

我也見過用ServerSocket,Socket實現的,隨便找本網路編程的書,上面都有類似的代碼

編程環境:JDK1.7,eclipse3.5

Ⅷ java網路編程 實現極簡單的聊天功能

在同一區域網環境是 應該是可以的! 程序裡面只要將Beijing.java里的IP地址改為Shanghai這台機器的地址 ,Shanghai.java里的IP地址改為Beijing這台機器的地址,應該就OK

Ⅸ java網路編程可以一個客戶端分多個線程通訊嗎。類似於QQ一邊聊天一邊發送文件

可以啊,完全沒問題啊

閱讀全文

與java網路編程聊天相關的資料

熱點內容
ios多選文件夾 瀏覽:907
加強行車調度命令管理 瀏覽:241
伺服器已禁用什麼意思 瀏覽:148
部隊命令回復 瀏覽:753
神奇寶貝伺服器地圖怎麼設置 瀏覽:380
加密演算法輸出固定長度 瀏覽:862
程序員去重慶還是武漢 瀏覽:121
伺服器如何撤銷網頁登錄限制 瀏覽:980
微信公眾平台php開發視頻教程 瀏覽:628
怎麼看蘋果授權綁定的app 瀏覽:255
壓縮機單級壓縮比 瀏覽:380
linux測試php 瀏覽:971
什麼時候梁旁邊需要加密箍筋 瀏覽:40
微信清粉軟體源碼 瀏覽:717
matlabdoc命令 瀏覽:550
如何去ping伺服器 瀏覽:75
ecshop安裝php55 瀏覽:817
javaword庫 瀏覽:958
php圖片路徑資料庫中 瀏覽:488
什麼是大擂台演算法 瀏覽:329