導航:首頁 > IDC知識 > java編寫伺服器

java編寫伺服器

發布時間:2021-01-16 06:13:25

1、Java用來編寫客戶端還是伺服器端?

兩者都可以...不過java的垃圾回收機制因為是自動的所以執行客戶端程序的時候效率特別慢...一般用於伺服器端或WEB開發...學java的重點就是以j2ee技術為核心的。想寫客戶端之類的用C語言是最佳的..不過內存處理機制全部自己編寫..難度不是一般的高。

2、如何用java編寫伺服器端和客戶端

B

3、如何用Java實現Web伺服器

如何用Java實現Web伺服器 一、HTTP協議的作用原理

WWW是以Internet作為傳輸媒介的一個應用系統,WWW網上最基本的傳輸單位是Web網頁。WWW的工作基於客戶機/伺服器計算模型,由Web 瀏覽器(客戶機)和Web伺服器(伺服器)構成,兩者之間採用超文本傳送協議(HTTP)進行通信。HTTP協議是基於TCP/IP協議之上的協議,是Web瀏覽器和Web伺服器之間的應用層協議,是通用的、無狀態的、面向對象的協議。HTTP協議的作用原理包括四個步驟:

(1) 連接:Web瀏覽器與Web伺服器建立連接,打開一個稱為socket(套接字)的虛擬文件,此文件的建立標志著連接建立成功。

(2) 請求:Web瀏覽器通過socket向Web伺服器提交請求。HTTP的請求一般是GET或POST命令(POST用於FORM參數的傳遞)。GET命令的格式為:

GET 路徑/文件名 HTTP/1.0

文件名指出所訪問的文件,HTTP/1.0指出Web瀏覽器使用的HTTP版本。

(3) 應答:Web瀏覽器提交請求後,通過HTTP協議傳送給Web伺服器。Web伺服器接到後,進行事務處理,處理結果又通過HTTP傳回給Web瀏覽器,從而在Web瀏覽器上顯示出所請求的頁面。

4、用JAVA編寫一個客戶機伺服器聊天程序

伺服器端(注意要先啟動伺服器端)

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

public class server extends Frame implements ActionListener {
Label label = new Label("交談內容");
Panel panel = new Panel();
TextField tf = new TextField(10);
TextArea ta = new TextArea();
ServerSocket server;
Socket client;
InputStream in;
OutputStream out;

public server() {
super("伺服器");
setSize(250, 250);
panel.add(label);
panel.add(tf);
tf.addActionListener(this);
add("North", panel);
add("Center", ta);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
show();
try {
server = new ServerSocket(4000);
client = server.accept();
ta.append("客戶機是:" + client.getInetAddress().getHostName() + "\n\n");
in =client.getInputStream();
out= client.getOutputStream();
} catch (IOException ioe) {
}
while (true) {
try {
byte[] buf = new byte[256];
in.read(buf);
String str = new String(buf);
ta.append("客戶機說:" + str + "\n\n");
} catch (IOException e) {
}
}
}

public void actionPerformed(ActionEvent e) {
try {
String str = tf.getText();
byte[] buf = str.getBytes();
tf.setText(null);
out.write(buf);
ta.append("我說:" + str + "\n");
} catch (IOException ioe) {
}
}

public static void main(String[] args) {
new server();
}
}

客戶端

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

public class client extends Frame implements ActionListener {
Label label = new Label("交談內容");
Panel panel = new Panel();
TextField tf = new TextField(10);
TextArea ta = new TextArea();
Socket client;
InputStream in;
OutputStream out;

public client() {
super("客戶機");
setSize(250, 250);
panel.add(label);
panel.add(tf);
tf.addActionListener(this);
add("North", panel);
add("Center", ta);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
show();
try {
client = new Socket(InetAddress.getLocalHost(), 4000);
ta.append("伺服器是:" + client.getInetAddress().getHostName() + "\n\n");
in = client.getInputStream();
out = client.getOutputStream();
} catch (IOException ioe) {
}
while (true) {
try {
byte[] buf = new byte[256];
in.read(buf);
String str = new String(buf);
ta.append("伺服器說:" + str + "\n");
} catch (IOException e) {
}
}
}

public void actionPerformed(ActionEvent e) {
try {
String str = tf.getText();
byte[] buf = str.getBytes();
tf.setText(null);
out.write(buf);
ta.append("我說:" + str + "\n");
} catch (IOException iOE) {
}
}

public static void main(String args[]) {
new client();
}
}

這個只能在自己一台電腦上先啟動伺服器再啟動客戶端才行,要想一台機子啟動伺服器端一台機子啟動客戶端需要把客戶端的 client = new Socket(InetAddress.getLocalHost(), 4000);改成 client = new Socket("伺服器Ip", 4000);(前提是兩台機子連在區域網裡面的)

5、如何用Java實現Web伺服器

如何用Java實現Web伺服器 一、HTTP協議的作用原理

WWW是以Internet作為傳輸媒介的一個應用系統,WWW網上最基本的傳輸單位是Web網頁。WWW的工作基於客戶機/伺服器計算模型,由Web 瀏覽器(客戶機)和Web伺服器(伺服器)構成,兩者之間採用超文本傳送協議(HTTP)進行通信。HTTP協議是基於TCP/IP協議之上的協議,是Web瀏覽器和Web伺服器之間的應用層協議,是通用的、無狀態的、面向對象的協議。HTTP協議的作用原理包括四個步驟:

(1) 連接:Web瀏覽器與Web伺服器建立連接,打開一個稱為socket(套接字)的虛擬文件,此文件的建立標志著連接建立成功。

(2) 請求:Web瀏覽器通過socket向Web伺服器提交請求。HTTP的請求一般是GET或POST命令(POST用於FORM參數的傳遞)。GET命令的格式為:

GET 路徑/文件名 HTTP/1.0

文件名指出所訪問的文件,HTTP/1.0指出Web瀏覽器使用的HTTP版本。

(3) 應答:Web瀏覽器提交請求後,通過HTTP協議傳送給Web伺服器。Web伺服器接到後,進行事務處理,處理結果又通過HTTP傳回給Web瀏覽器,從而在Web瀏覽器上顯示出所請求的頁面。

6、java編寫一個客戶/伺服器程序

下面是我自己寫的一個讀取並顯示txt文件的demo,希望對您有幫助。
public class Client {
public static void main(String[] args) {
ClientFrame f = new ClientFrame();
}
}

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ClientFrame extends JFrame implements ActionListener, ListSelectionListener{
private JList list = null;
private JButton sbtn = null;
private JButton cbtn = null;
private Vector v = null;
private JTextArea txt = null;
private Container control = null;
private Container btn = null;
private Socket client = null;
private DataInputStream reader = null;
private DataOutputStream writer = null;

public ClientFrame(){
this.list = new JList();
this.list.setBorder(BorderFactory.createTitledBorder("文件列表"));
this.list.addListSelectionListener(this);

this.sbtn = new JButton("顯示");
this.sbtn.addActionListener(this);
this.cbtn = new JButton("清除");
this.cbtn.addActionListener(this);

this.control = new Container();
this.control.setPreferredSize(new Dimension(150, 400));
this.control.setLayout(new BorderLayout());
this.control.add(new JScrollPane(this.list),BorderLayout.CENTER);
this.btn = new Container();
this.btn.setLayout(new GridLayout(1,2));
btn.add(sbtn);
btn.add(cbtn);
this.control.add(this.btn,BorderLayout.SOUTH);

this.txt = new JTextArea();
this.txt.setEditable(false);
this.txt.setSize(350, 400);

this.setTitle("客戶端");
this.setSize(500, 400);
this.setVisible(true);
Dimension displaySize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation((displaySize.width - this.getWidth()) / 2, (displaySize.height - this.getHeight()) / 2);
this.setLayout(new BorderLayout());
this.add(this.control,BorderLayout.WEST);
this.add(new JScrollPane(this.txt),BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

try {
//this.client = new Socket("192.168.32.34",6666);
this.client = new Socket("192.168.1.100",6666);
this.reader = new DataInputStream(client.getInputStream());
this.writer = new DataOutputStream(client.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public void actionPerformed(ActionEvent event){
if(event.getSource() == sbtn){
if(v == null){
v = new Vector();
}
else{
v.clear();
}

try {
writer.writeUTF("getfilelist");
writer.flush();
String t = reader.readUTF();
while( t != null && !t.equals("")){
v.add(t);
t = reader.readUTF();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
this.list.setListData(v);
}

if(event.getSource() == cbtn){
this.txt.setText("");
}
}

public void valueChanged(ListSelectionEvent e) {
int i = this.list.getSelectedIndex();
if (! this.list.getValueIsAdjusting() && i != -1) {
try {
writer.writeUTF("getfilecontent_" + i);
writer.flush();
String tmp = reader.readUTF();
this.txt.setText(tmp);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}

}

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;

public class Server {
static ArrayList<File> fileArray = new ArrayList<File>();
public static void main(String args[]) {
ServerSocket server = null;
Socket client = null;
String cmd = "";
try {
server = new ServerSocket(6666);
client = server.accept();

DataInputStream reader = new DataInputStream(client.getInputStream());
DataOutputStream writer = new DataOutputStream(client.getOutputStream());

while(true){
cmd = reader.readUTF();
System.out.println(cmd);
if(cmd.equals("getfilelist")){
fileArray.clear();
//fileArray = getFile(new File("D:/tmp"));
fileArray = getFile(new File("D:/學習/教程/學習筆記"));
String fn = "";
for(int k = 0; k < fileArray.size(); k ++){
fn = fileArray.get(k).getName();
writer.writeUTF(fn);
writer.flush();
}
writer.writeUTF("");
}
if(cmd.startsWith("getfilecontent_")){
int i = Integer.parseInt(cmd.split("_")[1]);
File f = fileArray.get(i);
Reader in = new InputStreamReader(new FileInputStream(f));
int tempbyte;
String str = "";
while ((tempbyte = in.read()) != -1) {
str += (char)tempbyte;
//System.out.println(str);
}
in.close();
writer.writeUTF(str);
}
}

} catch (IOException e) {
e.printStackTrace();
}
}

private static ArrayList<File> getFile(File f) {
File[] ff = f.listFiles();
for (File child : ff) {
if (child.isDirectory()) {
getFile(child);
} else {
fileArray.add(child);
}
}
return fileArray;
}
}

7、用java編寫一個獲取時間的伺服器

/**
* Created by IntelliJ IDEA.
* User: Knight_Sun
* Date: 2008-5-20
* Time: 9:19:09
* To change this template use File | Settings | File Templates.
*/

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

public class Showtime extends JFrame implements ActionListener {
private JButton timeBox;
private JTextField timeField;
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年M月d日 a h時m分s秒");

public Showtime(String title) throws HeadlessException {
super(title);
init();
doLay();
handleEvents();
}

private void init() {
timeBox = new JButton("刷新時間");
timeField = new JTextField(20);
}

private void doLay() {
Container container = getContentPane();
container.add(timeBox, BorderLayout.NORTH);
container.add(timeField, BorderLayout.SOUTH);

pack();
setVisible(true);
}

private void handleEvents() {
timeBox.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e) {
Timestamp nowtime=new Timestamp(System.currentTimeMillis());
timeField.setText(dateFormat.format(nowtime.getTime()));
}

public static void main(String[] args) {
new Showtime("Show Time");
}
}
看看是不是你要的效果,一個按鈕,點一下就顯示最新時間.

8、用Java編寫創建一對客戶端/伺服器程序,利用數據報將一個文件從一台主機傳送到另一

下面是我自己寫的一個讀取並顯示txt文件的demo,希望對您有幫助。
public class Client {
public static void main(String[] args) {
ClientFrame f = new ClientFrame();
}
}

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ClientFrame extends JFrame implements ActionListener, ListSelectionListener{
private JList list = null;
private JButton sbtn = null;
private JButton cbtn = null;
private Vector v = null;
private JTextArea txt = null;
private Container control = null;
private Container btn = null;
private Socket client = null;
private DataInputStream reader = null;
private DataOutputStream writer = null;

public ClientFrame(){
this.list = new JList();
this.list.setBorder(BorderFactory.createTitledBorder("文件列表"));
this.list.addListSelectionListener(this);

this.sbtn = new JButton("顯示");
this.sbtn.addActionListener(this);
this.cbtn = new JButton("清除");
this.cbtn.addActionListener(this);

this.control = new Container();
this.control.setPreferredSize(new Dimension(150, 400));
this.control.setLayout(new BorderLayout());
this.control.add(new JScrollPane(this.list),BorderLayout.CENTER);
this.btn = new Container();
this.btn.setLayout(new GridLayout(1,2));
btn.add(sbtn);
btn.add(cbtn);
this.control.add(this.btn,BorderLayout.SOUTH);

this.txt = new JTextArea();
this.txt.setEditable(false);
this.txt.setSize(350, 400);

this.setTitle("客戶端");
this.setSize(500, 400);
this.setVisible(true);
Dimension displaySize = Toolkit.getDefaultToolkit().getScreenSize(); 
this.setLocation((displaySize.width - this.getWidth()) / 2, (displaySize.height - this.getHeight()) / 2);
this.setLayout(new BorderLayout());
this.add(this.control,BorderLayout.WEST);
this.add(new JScrollPane(this.txt),BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

try {
//this.client = new Socket("192.168.32.34",6666);
this.client = new Socket("192.168.1.100",6666);
this.reader = new DataInputStream(client.getInputStream());
this.writer = new DataOutputStream(client.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public void actionPerformed(ActionEvent event){
 if(event.getSource() == sbtn){
 if(v == null){
 v = new Vector();
 }
 else{
 v.clear();
 }
 
 try {  
 writer.writeUTF("getfilelist");
 writer.flush();
 String t = reader.readUTF();
 while( t != null && !t.equals("")){
 v.add(t);
 t = reader.readUTF();
 }
 } catch (UnknownHostException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }
 this.list.setListData(v);
 }
 
 if(event.getSource() == cbtn){
 this.txt.setText("");
 }
 }

public void valueChanged(ListSelectionEvent e) {
int i = this.list.getSelectedIndex(); 
if (! this.list.getValueIsAdjusting() && i != -1) {
try {
writer.writeUTF("getfilecontent_" + i);
writer.flush();
String tmp = reader.readUTF();
this.txt.setText(tmp);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}

}

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;

public class Server {
static ArrayList<File> fileArray = new ArrayList<File>();
public static void main(String args[]) {
ServerSocket server = null;
Socket client = null;
String cmd = "";
try {
server = new ServerSocket(6666);
client = server.accept();

DataInputStream reader = new DataInputStream(client.getInputStream());
DataOutputStream writer = new DataOutputStream(client.getOutputStream());

while(true){
cmd = reader.readUTF();
System.out.println(cmd);
if(cmd.equals("getfilelist")){
fileArray.clear();
//fileArray = getFile(new File("D:/tmp"));
fileArray = getFile(new File("D:/學習/教程/學習筆記"));
String fn = "";
for(int k = 0; k < fileArray.size(); k ++){
fn = fileArray.get(k).getName();
writer.writeUTF(fn);
writer.flush();
}
writer.writeUTF("");
}
if(cmd.startsWith("getfilecontent_")){
int i = Integer.parseInt(cmd.split("_")[1]);
File f = fileArray.get(i);
Reader in = new InputStreamReader(new FileInputStream(f));
int tempbyte;
String str = "";
            while ((tempbyte = in.read()) != -1) {
             str += (char)tempbyte;
             //System.out.println(str);
            }
            in.close();
                writer.writeUTF(str);
}
}

} catch (IOException e) {
e.printStackTrace();
}
}

private static ArrayList<File> getFile(File f) {
File[] ff = f.listFiles();
for (File child : ff) {
if (child.isDirectory()) {
getFile(child);
} else {
fileArray.add(child);
}
}
return fileArray;
}
}

9、java編伺服器與客戶端之間的一個程序(要求如下)

import java.net.Socket;
import java.io.*;
public class Client{
private Socket socket=null;
private BufferedReader br;
private PrintWriter pw;
private boolean flag=true;
public Client(){
socket=new Socket("localhost",8000);
br=socket.getInputStream();
String str=br.readLine();
while(!str.equals("")&&flag){
System.out.println("Server:"+str);
InputStream is=new InuptStream(System.in);
BufferedReader br1=new BufferedReader(is);
String message=br1.readLine();
OutputStream os=socket.getOutputStream();
pw=new PrintWriter(os);
if(!message.equals("")&&!message.equals("bye"))
pw.println(message);
else
flag=false;
}
br.close();
pw.close();
}
public static void main(String[] args){
new Client();
}
}

//伺服器程序
import java.io.*;
import java.net.*;
public class Server{
private ServerSocket ss;
private BufferedReader br;
private PrintWriter pw;
private boolean flag=true;
public Server(){
ss=new ServerSocket(8000);
Socket s=ss.getSocket();
br=s.getInputStream();
pw=s.getOutputStream();
String message="";
message=br.readLine();
while(flag&&message.equals("")){
pw.println(Please enter your name);
pw.println("echo="+message);
if(message.equals("bye"))
flag=false;
}
}
}

與java編寫伺服器相關的知識