Ⅰ java使用tcp協議傳送資料庫讀取的數據
。。。。先自己看網路編程的資料:
最簡單的思路:
伺服器端:
偵聽-》偵聽到連接-》獲得客戶端的查詢請求-》查詢資料庫-》發送數據給客戶端
客戶端:
連接伺服器-》發送查詢請求-》等待數據-》讀取數據
Ⅱ java網路編程中,對於客戶端和伺服器的tcp連接,如果客戶端異常斷開連接,伺服器端如何獲知,有什麼方法
這個得用java心跳處理機制。就是客戶端每隔一段時間向伺服器發送指定信息,如果伺服器沒有收到客服端發來的信息,這時伺服器和客服端連接就已經斷開。具體的心跳實現網路上很多。
Ⅲ Java 請教TCP網路編程裡面的兩個方法的使用!
package chatClient;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JTextArea;
import org.apache.log4j.Logger;
import DownLoad.*;
import config.*;
public class ChatClient extends JFrame {
private static Logger log=Logger.getLogger(ChatClient.class);
Socket s = null;
TextField tf = new TextField();
TextArea ta = new TextArea(null,11,50,TextArea.SCROLLBARS_VERTICAL_ONLY);
Panel p=new Panel(new GridLayout(2,6,2,3));
Label l3=new Label("下裁的文件名:");
TextField tf1 = new TextField();
Button b3=new Button("下載");
Label l4=new Label("上傳的文件名:");
TextField tf2 = new TextField();
Button b4=new Button("上傳");
Label l1=new Label("用戶名:");
Label l2=new Label("密碼:");
TextField name = new TextField();
JPasswordField pwd=new JPasswordField();
Button b1=new Button("連接");
Button b2=new Button("斷開");
SimpleDateFormat st=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DataOutputStream dos = null;
DataInputStream dis = null;
String cname;
boolean success=false;
boolean start=true;
public static void main(String[] args) {
new ChatClient().launchFrame();
log.debug("test");
log.info("info");
log.error("error");
}
public void launchFrame(){
setLocation(300,333);
p.add(l1);
p.add(name);
p.add(l2);
p.add(pwd);
p.add(b1);
p.add(b2);
p.add(l3);p.add(tf1);p.add(b3);p.add(l4);p.add(tf2);p.add(b4);
ta.setCaretPosition(ta.getText().length());
add(p,BorderLayout.NORTH);
add(tf,BorderLayout.SOUTH);
add(ta,BorderLayout.CENTER);
pack();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
if(!success){disconnect();}
System.exit(0);
}
});
tf.addActionListener(new TFListener());
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(check()){
connect();
if(!success){
new Thread(new Receve()).start();
}
}else{
JOptionPane.showMessageDialog(null, "用戶名或密碼錯誤,請確認後重輸!");
}
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
disconnect();
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(tf1.getText().equals("")){
JOptionPane.showMessageDialog(null, "輸入要下裁的文件名!");
}else{
new DownloadStartupC().start(tf1.getText());
}
}
});
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(tf2.getText().equals("")){
JOptionPane.showMessageDialog(null, "請輸入要上傳的文件名和路徑!");
}else{
new DownloadStartup().start(tf2.getText());
}
}
});
setVisible(true);
this.setResizable(false);
}
public boolean check(){
cname=name.getText();
String pwd1=pwd.getText();
String pwd2=FileUtil.getMemberData(cname);
if(pwd1.equals(pwd2)){
return true;
}else{
return false;
}
}
public void connect(){
start=true;
try {
s= new Socket (FileUtil.getServerInfoData("serverhost"),Integer.parseInt(FileUtil.getServerInfoData("serverport")));
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
dos.writeUTF(cname+"登錄 "+st.format(new Date()));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "伺服器端異常,請稍後重試!");
success=true;
return;
}
success=false;
b1.setEnabled(false);
}
public void disconnect (){
try {
if(dos!=null){
dos.writeUTF(cname+"退出 "+st.format(new Date()));
dos.close();}
if(s!=null){
s.close();}
} catch (IOException e) {
e.printStackTrace();
}
success=true;
b1.setEnabled(true);
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tf.getText();
tf.setText("");
try {
dos.writeUTF(cname+":"+str);
dos.flush();
} catch (Exception e1) {
log.info(e.toString());
JOptionPane.showMessageDialog(null, "未連接,請連接後再發言!");
}
}
}
private class Receve implements Runnable{
public void run() {
try{
while(start){
String s= dis.readUTF();
//if(s.equals("伺服器已關閉,請重新登錄!")){
// start=false;
// b1.setEnabled(true);
// }
ta.setText(ta.getText()+s+'\n');
ta.setCaretPosition(ta.getText().length());
}
} catch(IOException e){
start=false;
b1.setEnabled(true);
// e.printStackTrace();
}
}
}
}
package ChatServer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import DownLoad.DownloadStartup;
import config.FileUtil;
public class ChatServer extends Frame {
ServerSocket ss = null;
Socket s = null;
boolean start = false;
DataInputStream dis = null;
List clients = new ArrayList();
TextArea ta = new TextArea(null,11,50,TextArea.SCROLLBARS_VERTICAL_ONLY);
JPanel p = new JPanel(new GridLayout(2, 2, 5, 5));
TextField tf = new TextField();
JButton b3 = new JButton("上傳");
JButton b1 = new JButton("start");
JButton b2 = new JButton("stop");
class Client implements Runnable {
private Socket s = null;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean stat = false;
public Client(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
stat = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch (Exception e) {
clients.remove(this);
// e.printStackTrace();
}
}
public void run() {
Client c = null;
try {
while (stat) {
String str = dis.readUTF();
ta.setText(ta.getText()+str+"\n");
ta.setCaretPosition(ta.getText().length());
for (int i = 0; i < clients.size(); i++) {
c = (Client) clients.get(i);
c.send(str);
}
// System.out.println(clients.size());
}
} catch (Exception e) {
//System.out.println("closed!");
} finally {
try {
if (dos != null)
dos.close();
if (dis != null)
dis.close();
if (s != null)
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new ChatServer().launchFrame();
}
public void launchFrame() {
setLocation(300, 333);
this.setSize(300, 300);
this.setTitle("伺服器端");
p.add(b1);
p.add(b2);
p.add(tf);
p.add(b3);
ta.setCaretPosition(ta.getText().length());
add(p, BorderLayout.SOUTH);
add(ta, BorderLayout.CENTER);
pack();
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Thread t=new Thread(new DisConnection());
t.start();
Client c = null;
for (int i = 0; i < clients.size(); i++) {
c = (Client) clients.get(i);
c.send("伺服器已關閉,請稍後重新登錄!");
}
System.exit(0);
}
});
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setTitle("伺服器啟動");
Thread t=new Thread(new Connection());
t.start();
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setTitle("伺服器關閉");
Thread t=new Thread(new DisConnection());
t.start();
Client c = null;
for (int i = 0; i < clients.size(); i++) {
c = (Client) clients.get(i);
c.send("伺服器已關閉,請稍後重新登錄!");
}
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// System.out.println(tf.getText());
if(tf.getText().equals("")){
JOptionPane.showMessageDialog(null, "請輸入要上傳的文件名和路徑!");
}else{
new DownloadStartup().start(tf.getText());}
}
});
setVisible(true);
}
private class Connection implements Runnable{
public void run() {
try {
ss = new ServerSocket(Integer.parseInt(FileUtil.getServerInfoData("serverport")));
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "伺服器啟動不成功,重試!");
}
try {
start = true;
while (start) {
s = ss.accept();
Client c = new Client(s);
// System.out.println("A Client connected!");
new Thread(c).start();
clients.add(c);
}
} catch (Exception e) {
System.out.println("伺服器關閉");
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private class DisConnection implements Runnable{
public void run() {
try {
if(s!=null){
s.close();
}
if(ss!=null){
ss.close();
System.out.println("close");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream out=new FileOutputStream("Chathistory/history.txt");
out.write(ta.getText().getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
給你個例子 自己看吧
兩個類 可以運行的 你運行起來看看
Ⅳ 怎樣理解java中的網路編程
Java中的網路編程主要是Java的Socket編程,屬於JavaEE中的高級的部分,以下內容是對java網路編程的一個小結,代碼都是經過編譯調試的
C/S程序應用:客戶/伺服器模式,如QQ客戶端,客戶端連到伺服器上,一個C/S模式的應用必須有兩套程序,一個是客戶端的程序,一個是伺服器程序。
B/S程序應用:瀏覽器/伺服器模式,如當下的各種網站都是B/S模式,所有的程序代碼都在伺服器上,用戶通過瀏覽器去訪問。
C/S程序分為兩種:
基於TCP協議:Socket(套接字), 可靠的編程: A->B 如打電話先建立連接
基於UDP協議:不可靠,如簡訊功能。
如果編寫一個TCP程序需要JAVA的兩個包支持:
java.net.*: 主要提供網路支持;
|-ServerSocket類:伺服器端程序
|-Socket類:客戶端程序
java,io.*:傳遞信息流
客戶端的兩個功能:
1.建立Socket
2.接收輸入的命令(輸入流)->網路上傳輸的程序考的是位元組流
以下是伺服器端,客戶端的兩個事常式序,伺服器端想客戶端輸出Hello word, 客戶端接收並顯示;
伺服器程序:
importjava.io.*;
importjava.net.*;
publicclassTCPSever{
/**
*@paramargs
*@throwsIOException
*/
publicstaticvoidmain(String[]args)throwsIOException{
//TODOAuto-generatedmethodstub
//使用ServerSocket
ServerSocketserver=newServerSocket(8000);
//每個用戶在程序中就是一個Socket
Socketclient=null;
//等待客戶端連接
client=server.accept();
//像客戶端列印信息
PrintWriterout=null;
//准被向客戶端列印信息
out=newPrintWriter(client.getOutputStream());
out.println("HelloWorld");
out.close();
client.close();
server.close();
}
}
客戶端程序:
packageClient;
importjava.io.*;
importjava.net.*;
publicclassTCPClient{
/**
*@paramargs
*@throwsIOException
*@throwsUnknownHostException
*/
publicstaticvoidmain(String[]args)throwsUnknownHostException,IOException{
//TODOAuto-generatedmethodstub
//表示一個客戶端的Socket
Socketclient=null;
//表示一個客戶端的輸入信息
BufferedReaderbuf=null;
client=newSocket("localhost",8000);
buf=newBufferedReader(newInputStreamReader(client.getInputStream()));
System.out.println(buf.readLine());
buf.close();
client.close();
}
}
在JDK中也准備了兩個專門用於實現UDP的類
1.DatagramScoket
2.DatagramPacket
伺服器端程序:
packageClient;
importjava.io.*;
importjava.net.*;
publicclassTCPClient{
/**
*@paramargs
*@throwsIOException
*@throwsUnknownHostException
*/
publicstaticvoidmain(String[]args)throwsUnknownHostException,IOException{
//TODOAuto-generatedmethodstub
//表示一個客戶端的Socket
Socketclient=null;
//表示一個客戶端的輸入信息
BufferedReaderbuf=null;
client=newSocket("localhost",8000);
buf=newBufferedReader(newInputStreamReader(client.getInputStream()));
System.out.println(buf.readLine());
buf.close();
client.close();
}
}
客戶端程序:
packageTest4;
importjava.io.*;
importjava.net.*;
publicclassUDPClient{
/**
*@paramargs
*@throwsIOException
*/
publicstaticvoidmain(String[]args)throwsIOException{
//TODOAuto-generatedmethodstub
DatagramSocketds=null;
DatagramPacketdp=null;
byte[]b=newbyte[1024];
ds=newDatagramSocket(8000);
dp=newDatagramPacket(b,b.length);
ds.receive(dp);
Stringstr=newString(dp.getData(),0,dp.getLength());
System.out.println(str);
}
}
Ⅳ Java網路編程需要導入()包中的類與介面
咨詢記錄 · 回答於2021-12-26
Ⅵ Java網路編程tcp,新手問題,
if(line.equals("over")){break;}//-------------------------------- 接收第一種結束標記。
改成
if(line.equals("over")){
so.shutdownInput();
break;}
Ⅶ java 網路編程: 如何實現客戶端與客戶端之間的之間通信
伺服器告知雙方對方的ip地址,並協調由哪一方主動連接。
如 協調結果是: 把c2的地址告訴c1,讓c1主動連接c2,讓c2打開埠等待連接。
要考慮認證問題,比如c2如何知道連接上來的是c1,而不是其他人,就需要有認證機制。
另外要考慮內網問題。由於從外部連接內網裡面的IP地址是相當繁瑣復雜的,所以需要特別的機制處理。
Ⅷ java的tcp網路編程問題
在伺服器端
ow.write("welcome".getBytes());
後添加
ow.flush();
Ⅸ 使用Java網路編程編寫SIP消息的收發,TCP和UDP有什麼區別
目前通用的編程語言有兩種形式:匯編語言和高級語言。
匯編語言的實質和機器語言是相同的,都是直接對硬體操作,只不過指令採用了英文縮寫的標識符,更容易識別和記憶。它同樣需要編程者將每一步具體的操作用命令的形式寫出來。匯編程序通常由三部分組成:指令、偽指令和宏指令。匯編程序的每一句指令只能對應實際操作過程中的一個很細微的動作,例如移動、自增,因此匯編源程序一般比較冗長、復雜、容易出錯,而且使用匯編語言編程需要有更多的計算機專業知識,但匯編語言的優點也是顯而易見的,用匯編語言所能完成的操作不是一般高級語言所能實現的,而且源程序經匯編生成的可執行文件不僅比較小,而且執行速度很快。
高級語言是目前絕大多數編程者的選擇。和匯編語言相比,它不但將許多相關的機器指令合成為單條指令,並且去掉了與具體操作有關但與完成工作無關的細節,例如使用堆棧、寄存器等,這樣就大大簡化了程序中的指令。同時,由於省略了很多細節,編程者也就不需要有太多的專業知識。
高級語言主要是相對於匯編語言而言,它並不是特指某一種具體的語言,而是包括了很多編程語言,如目前流行的VB、VC、FoxPro、Delphi等,這些語言的語法、命令格式都各不相同。
高級語言所編制的程序不能直接被計算機識別,必須經過轉換才能被執行,按轉換方式可將它們分為兩類:
解釋類:執行方式類似於我們日常生活中的「同聲翻譯」,應用程序源代碼一邊由相應語言的解釋器「翻譯」成目標代碼(機器語言),一邊執行,因此效率比較低,而且不能生成可獨立執行的可執行文件,應用程序不能脫離其解釋器,但這種方式比較靈活,可以動態地調整、修改應用程序。
編譯類:編譯是指在應用源程序執行之前,就將程序源代碼「翻譯」成目標代碼(機器語言),因此其目標程序可以脫離其語言環境獨立執行,使用比較方便、效率較高。但應用程序一旦需要修改,必須先修改源代碼,再重新編譯生成新的目標文件(* .OBJ)才能執行,只有目標文件而沒有源代碼,修改很不方便。現在大多數的編程語言都是編譯型的,例如Visual C++、Visual Foxpro、Delphi等。