當前位置:首頁 » 文件管理 » javasocket上傳

javasocket上傳

發布時間: 2022-04-16 20:18:13

1. 利用java socket實現文件傳輸

1.伺服器端

package sterning;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {
int port = 8821;

void start() {
Socket s = null;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
// 選擇進行傳輸的文件
String filePath = "D:\\lib.rar";
File fi = new File(filePath);

System.out.println("文件長度:" + (int) fi.length());

// public Socket accept() throws
// IOException偵聽並接受到此套接字的連接。此方法在進行連接之前一直阻塞。

s = ss.accept();
System.out.println("建立socket鏈接");
DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
dis.readByte();

DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
DataOutputStream ps = new DataOutputStream(s.getOutputStream());
//將文件名及長度傳給客戶端。這里要真正適用所有平台,例如中文名的處理,還需要加工,具體可以參見Think In Java 4th里有現成的代碼。
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long) fi.length());
ps.flush();

int bufferSize = 8192;
byte[] buf = new byte[bufferSize];

while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}

if (read == -1) {
break;
}
ps.write(buf, 0, read);
}
ps.flush();
// 注意關閉socket鏈接哦,不然客戶端會等待server的數據過來,
// 直到socket超時,導致數據不完整。
fis.close();
s.close();
System.out.println("文件傳輸完成");
}

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

public static void main(String arg[]) {
new ServerTest().start();
}
}

2.socket的Util輔助類

package sterning;

import java.net.*;
import java.io.*;

public class ClientSocket {
private String ip;

private int port;

private Socket socket = null;

DataOutputStream out = null;

DataInputStream getMessageStream = null;

public ClientSocket(String ip, int port) {
this.ip = ip;
this.port = port;
}

/** *//**
* 創建socket連接
*
* @throws Exception
* exception
*/
public void CreateConnection() throws Exception {
try {
socket = new Socket(ip, port);
} catch (Exception e) {
e.printStackTrace();
if (socket != null)
socket.close();
throw e;
} finally {
}
}

public void sendMessage(String sendMessage) throws Exception {
try {
out = new DataOutputStream(socket.getOutputStream());
if (sendMessage.equals("Windows")) {
out.writeByte(0x1);
out.flush();
return;
}
if (sendMessage.equals("Unix")) {
out.writeByte(0x2);
out.flush();
return;
}
if (sendMessage.equals("Linux")) {
out.writeByte(0x3);
out.flush();
} else {
out.writeUTF(sendMessage);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
if (out != null)
out.close();
throw e;
} finally {
}
}

public DataInputStream getMessageStream() throws Exception {
try {
getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
return getMessageStream;
} catch (Exception e) {
e.printStackTrace();
if (getMessageStream != null)
getMessageStream.close();
throw e;
} finally {
}
}

public void shutDownConnection() {
try {
if (out != null)
out.close();
if (getMessageStream != null)
getMessageStream.close();
if (socket != null)
socket.close();
} catch (Exception e) {

}
}
}

3.客戶端

package sterning;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;

public class ClientTest {
private ClientSocket cs = null;

private String ip = "localhost";// 設置成伺服器IP

private int port = 8821;

private String sendMessage = "Windwos";

public ClientTest() {
try {
if (createConnection()) {
sendMessage();
getMessage();
}

} catch (Exception ex) {
ex.printStackTrace();
}
}

private boolean createConnection() {
cs = new ClientSocket(ip, port);
try {
cs.CreateConnection();
System.out.print("連接伺服器成功!" + "\n");
return true;
} catch (Exception e) {
System.out.print("連接伺服器失敗!" + "\n");
return false;
}

}

private void sendMessage() {
if (cs == null)
return;
try {
cs.sendMessage(sendMessage);
} catch (Exception e) {
System.out.print("發送消息失敗!" + "\n");
}
}

private void getMessage() {
if (cs == null)
return;
DataInputStream inputStream = null;
try {
inputStream = cs.getMessageStream();
} catch (Exception e) {
System.out.print("接收消息緩存錯誤\n");
return;
}

try {
//本地保存路徑,文件名會自動從伺服器端繼承而來。
String savePath = "E:\\";
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int passedlen = 0;
long len=0;

savePath += inputStream.readUTF();
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath))));
len = inputStream.readLong();

System.out.println("文件的長度為:" + len + "\n");
System.out.println("開始接收文件!" + "\n");

while (true) {
int read = 0;
if (inputStream != null) {
read = inputStream.read(buf);
}
passedlen += read;
if (read == -1) {
break;
}
//下面進度條本為圖形界面的prograssBar做的,這里如果是打文件,可能會重復列印出一些相同的百分比
System.out.println("文件接收了" + (passedlen * 100/ len) + "%\n");
fileOut.write(buf, 0, read);
}
System.out.println("接收完成,文件存為" + savePath + "\n");

fileOut.close();
} catch (Exception e) {
System.out.println("接收消息錯誤" + "\n");
return;
}
}

public static void main(String arg[]) {
new ClientTest();
}
}

2. java socket 文件上傳到部署服務的電腦上。。。

用socket搭建C/S模式,你的客戶端、服務端都在A上,你在B上怎麼與A通信,最起碼你將客戶端放在B上,服務端放在A,然後在B上通過客戶端與A的服務端通信,然後可以將B端(客戶端)的文件通過服務端保存到A上。

3. 用java socket實現一個伺服器對多個客戶端的文件傳輸

通過socket可以用如下方式進行。
1.啟動服務端代碼。
2.啟動客戶端自動連接服務端。
3.服務端上傳文件,保存文件和路徑。
4.將路徑發送給連接服務端的客戶端。

4. java使用socket文件上傳

for(int size=0;size!=-1;size=fis.read(buf)){
output.write(buf,0,size);
output.flush();
}
for(int size=0;size!=-1;size=fis.read(buf))
在buf中讀取位元組;當buf沒有內容了,返回的-1;在這個之前,一直在循環;
output.write(buf,0,size);
output.flush();
把buf中道0開始到size個位元組的內容寫入輸出流緩沖中
並用 flush()確認發送到輸出流中了;
我的意見是output.write(buf,0,size);
改為output.write(buf);
你接受數據部分代碼怎麼寫的,是不是size等於一個大於1024的整數了而出錯

5. 求javasocket 上傳文件例子

//Client.java文件中的內容

import java.io.* ;
import java.net.* ;
public class Client {

public static final int BUF_SIZE = 1024 ;

public static void main(String args[]) {
Client s = new Client() ;
s.start() ;
}

public void start() {
run() ;
}

public void run() {
try {
//聲明變數
File f = new File("b.txt") ;
FileInputStream fis = new FileInputStream(f) ;
OutputStream os = null ;
PrintWriter pw = null ;
Socket s = null ;
byte buf[] = new byte[BUF_SIZE] ;
int count = 0 ;

//連接伺服器
s = new Socket("127.0.0.1" ,1989) ;

System.out.println ("已經連接上伺服器..") ;

os = s.getOutputStream() ;
pw = new PrintWriter(os ,true) ;

//發送文件大小
int size = fis.available() ;
pw.println(size) ;
System.out.println ("發送文件大小" + size) ;

System.out.println ("開始發送文件內容..") ;
//發送文件內容
count = size / BUF_SIZE ;
if(size % BUF_SIZE != 0)
count ++ ;

for (int i = 0; i<count; i++) {
int asize = fis.read(buf ,0 ,BUF_SIZE) ;
os.write(buf ,0 ,asize) ;
}
System.out.println ("文件內容發送完畢!") ;
}
catch (Exception ex) {
ex.printStackTrace() ;
}
}

}

//Server.java文件中的內容
import java.io.* ;
import java.net.* ;

public class Server {
public static final int BUF_SIZE = 1024 ;

public static void main(String args[]) {
Server s = new Server() ;
s.start() ;
}

public void start() {
run() ;
}

public void run() {
try {
//聲明變數
File f = new File("a.txt") ;
FileOutputStream fos = new FileOutputStream(f ,true) ;
InputStream is = null ;
BufferedReader br = null ;
Socket ss = null ;
byte buf[] = new byte[BUF_SIZE] ;
int count = 0 ;
ServerSocket s = new ServerSocket(1989) ;
System.out.println ("等待用戶連接...") ;

//接受客戶端請求
ss= s.accept() ;

System.out.println ("用戶連接了上來!") ;

is = ss.getInputStream() ;
br = new BufferedReader(new InputStreamReader(is)) ;

//獲得文件大小
String a = br.readLine() ;
int size = Integer.parseInt(a) ;
System.out.println ("接收文件大小為:" + size) ;

count = size / BUF_SIZE ;
if(size % BUF_SIZE != 0)
count ++ ;
System.out.println ("開始接收文件內容..") ;
for (int i = 0; i<count; i++) {
int asize = is.read(buf ,0 ,BUF_SIZE) ;
fos.write(buf , 0 ,asize) ;
}
System.out.println ("文件接收完畢..") ;
}
catch (Exception ex) {
ex.printStackTrace() ;

}
}

}

PS:Client.java所在的目錄中要有一個名為"a.txt"的文件作為傳送的文件

6. java socket如何實現一次傳送多個文件

很簡單,就是把多個文件「變成」一個文件傳送就可以了,每個文件都是一個流,把這些流輸入到一個流中合並流傳輸即可,這個是基本思路。實現差不多以下兩個方法
1、直接流拼接,循環要傳輸的文件列表,多個InputStream,然後輸出到一個OutputStream,這個out就是發送數據的埠,為了接收端能夠識別每個文件從而分割流,需要每個流中結尾添加分隔符。其實這就是HTTP文件上傳的做法。
2、就比較簡單了,職業使用ZIP工具包吧需要傳輸的多文件壓縮成一個文件傳輸,接收端直接解壓縮就完事。
需要注意的是,發送多文件上傳你需要提取計算好總傳輸量位元組大小放在傳輸報文頭部告訴接收端你要發送的數據有多大,不然接收端可能無法完整接收數據。

7. Java socket上傳文件,伺服器的文件比上傳的多了一行(最後一行)。不知道怎麼處理(代碼如下)

inti=0;
while((line=clientIn.readLine())!=null){
if(i++!=0)
bw.newLine();
bw.write(line);
bw.flush();
}

8. 怎麼用java的socket進行文件傳輸誰能給個簡單的例子,包括發送端和接收端。

java中的網路信息傳輸方式是基於TCP協議或者UD協議P的,socket是基於TCP協議的

例子1
(1)客戶端程序:
import java.io.*;
import java.net.*;
public class Client
{ public static void main(String args[])
{ String s=null;
Socket mysocket;
DataInputStream in=null;
DataOutputStream out=null;
try{
mysocket=new Socket("localhost",4331);
in=new DataInputStream(mysocket.getInputStream());
out=new DataOutputStream(mysocket.getOutputStream());
out.writeUTF("你好!");//通過 out向"線路"寫入信息。
while(true)
{
s=in.readUTF();//通過使用in讀取伺服器放入"線路"里的信息。堵塞狀態,
//除非讀取到信息。
out.writeUTF(":"+Math.random());
System.out.println("客戶收到:"+s);
Thread.sleep(500);
}
}
catch(IOException e)
{ System.out.println("無法連接");
}
catch(InterruptedException e){}
}
}
(2)伺服器端程序:
import java.io.*;import java.net.*;
public class Server
{ public static void main(String args[])
{ ServerSocket server=null;
Socket you=null;String s=null;
DataOutputStream out=null;DataInputStream in=null;
try{ server=new ServerSocket(4331);}
catch(IOException e1){System.out.println("ERRO:"+e1);}
try{ you=server.accept();
in=new DataInputStream(you.getInputStream());
out=new DataOutputStream(you.getOutputStream());
while(true)
{
s=in.readUTF();// 通過使用in讀取客戶放入"線路"里的信息。堵塞狀態,
//除非讀取到信息。

out.writeUTF("你好:我是伺服器");//通過 out向"線路"寫入信息.
out.writeUTF("你說的數是:"+s);
System.out.println("伺服器收到:"+s);
Thread.sleep(500);
}
}
catch(IOException e)
{ System.out.println(""+e);
}
catch(InterruptedException e){}
}
}

例子(2)
(1) 客戶端
import java.net.*;import java.io.*;
import java.awt.*;import java.awt.event.*;
import java.applet.*;
public class Computer_client extends Applet implements Runnable,ActionListener
{ Button 計算;TextField 輸入三邊長度文本框,計算結果文本框;
Socket socket=null;
DataInputStream in=null; DataOutputStream out=null;
Thread thread;
public void init()
{ setLayout(new GridLayout(2,2));
Panel p1=new Panel(),p2=new Panel();
計算=new Button(" 計算");
輸入三邊長度文本框=new TextField(12);計算結果文本框=new TextField(12);
p1.add(new Label("輸入三角形三邊的長度,用逗號或空格分隔:"));
p1.add( 輸入三邊長度文本框);
p2.add(new Label("計算結果:"));p2.add(計算結果文本框);p2.add(計算);
計算.addActionListener(this);
add(p1);add(p2);
}
public void start()
{ try
{ //和小程序所駐留的伺服器建立套接字連接:
socket = new Socket(this.getCodeBase().getHost(), 4331);
in =new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
}
catch (IOException e){}
if(thread == null)
{ thread = new Thread(this);
thread.start();
}
}
public void run()
{ String s=null;
while(true)
{ try{ s=in.readUTF();//堵塞狀態,除非讀取到信息。

計算結果文本框.setText(s);
}
catch(IOException e)
{ 計算結果文本框.setText("與伺服器已斷開");
break;
}
}
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==計算)
{ String s=輸入三邊長度文本框.getText();
if(s!=null)
{ try { out.writeUTF(s);
}
catch(IOException e1){}
}
}
}
}

(2) 伺服器端
import java.io.*;import java.net.*;
import java.util.*;import java.sql.*;
public class Computer_server
{ public static void main(String args[])
{ ServerSocket server=null;Server_thread thread;
Socket you=null;
while(true)
{ try{ server=new ServerSocket(4331);
}
catch(IOException e1)
{ System.out.println("正在監聽"); //ServerSocket對象不能重復創建。
}
try{ you=server.accept();
System.out.println("客戶的地址:"+you.getInetAddress());
}
catch (IOException e)
{ System.out.println("正在等待客戶");
}
if(you!=null)
{ new Server_thread(you).start(); //為每個客戶啟動一個專門的線程。
}
else
{ continue;
}
}
}
}
class Server_thread extends Thread
{ Socket socket;Connection Con=null;Statement Stmt=null;
DataOutputStream out=null;DataInputStream in=null;int n=0;
String s=null;
Server_thread(Socket t)
{ socket=t;
try { in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
}
catch (IOException e)
{}
}
public void run()
{ while(true)
{ double a[]=new double[3] ;int i=0;
try{ s=in.readUTF();堵塞狀態,除非讀取到信息。

StringTokenizer fenxi=new StringTokenizer(s," ,");
while(fenxi.hasMoreTokens())
{ String temp=fenxi.nextToken();
try{ a[i]=Double.valueOf(temp).doubleValue();i++;
}
catch(NumberFormatException e)
{ out.writeUTF("請輸入數字字元");
}
}
double p=(a[0]+a[1]+a[2])/2.0;
out.writeUTF(" "+Math.sqrt(p*(p-a[0])*(p-a[1])*(p-a[2])));
sleep(2);
}
catch(InterruptedException e){}
catch (IOException e)
{ System.out.println("客戶離開");
break;
}
}
}
}

這些例子都是Java2實用教程上的.

9. java socket傳送文件

客戶端代碼如下:

importjava.io.DataOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.net.InetSocketAddress;
importjava.net.Socket;

/**
*文件發送客戶端主程序
*@authoradmin_Hzw
*
*/
publicclassBxClient{

/**
*程序main方法
*@paramargs
*@throwsIOException
*/
publicstaticvoidmain(String[]args)throwsIOException{
intlength=0;
doublesumL=0;
byte[]sendBytes=null;
Socketsocket=null;
DataOutputStreamdos=null;
FileInputStreamfis=null;
booleanbool=false;
try{
Filefile=newFile("D:/天啊.zip");//要傳輸的文件路徑
longl=file.length();
socket=newSocket();
socket.connect(newInetSocketAddress("127.0.0.1",48123));
dos=newDataOutputStream(socket.getOutputStream());
fis=newFileInputStream(file);
sendBytes=newbyte[1024];
while((length=fis.read(sendBytes,0,sendBytes.length))>0){
sumL+=length;
System.out.println("已傳輸:"+((sumL/l)*100)+"%");
dos.write(sendBytes,0,length);
dos.flush();
}
//雖然數據類型不同,但JAVA會自動轉換成相同數據類型後在做比較
if(sumL==l){
bool=true;
}
}catch(Exceptione){
System.out.println("客戶端文件傳輸異常");
bool=false;
e.printStackTrace();
}finally{
if(dos!=null)
dos.close();
if(fis!=null)
fis.close();
if(socket!=null)
socket.close();
}
System.out.println(bool?"成功":"失敗");
}
}

服務端代碼如下:

importjava.io.DataInputStream;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.net.ServerSocket;
importjava.net.Socket;
importjava.util.Random;
importcom.boxun.util.GetDate;


/**
*接收文件服務
*@authoradmin_Hzw
*
*/
publicclassBxServerSocket{

/**
*工程main方法
*@paramargs
*/
publicstaticvoidmain(String[]args){
try{
finalServerSocketserver=newServerSocket(48123);
Threadth=newThread(newRunnable(){
publicvoidrun(){
while(true){
try{
System.out.println("開始監聽...");
/*
*如果沒有訪問它會自動等待
*/
Socketsocket=server.accept();
System.out.println("有鏈接");
receiveFile(socket);
}catch(Exceptione){
System.out.println("伺服器異常");
e.printStackTrace();
}
}
}
});
th.run();//啟動線程運行
}catch(Exceptione){
e.printStackTrace();
}
}

publicvoidrun(){
}

/**
*接收文件方法
*@paramsocket
*@throwsIOException
*/
publicstaticvoidreceiveFile(Socketsocket)throwsIOException{
byte[]inputByte=null;
intlength=0;
DataInputStreamdis=null;
FileOutputStreamfos=null;
StringfilePath="D:/temp/"+GetDate.getDate()+"SJ"+newRandom().nextInt(10000)+".zip";
try{
try{
dis=newDataInputStream(socket.getInputStream());
Filef=newFile("D:/temp");
if(!f.exists()){
f.mkdir();
}
/*
*文件存儲位置
*/
fos=newFileOutputStream(newFile(filePath));
inputByte=newbyte[1024];
System.out.println("開始接收數據...");
while((length=dis.read(inputByte,0,inputByte.length))>0){
fos.write(inputByte,0,length);
fos.flush();
}
System.out.println("完成接收:"+filePath);
}finally{
if(fos!=null)
fos.close();
if(dis!=null)
dis.close();
if(socket!=null)
socket.close();
}
}catch(Exceptione){
e.printStackTrace();
}
}
}

10. 如何使用java socket來傳輸自定義的數據包

以下分四點進行描述:

1,什麼是Socket
網路上的兩個程序通過一個雙向的通訊連接實現數據的交換,這個雙向鏈路的一端稱為一個Socket。Socket通常用來實現客戶方和服務方的連接。Socket是TCP/IP協議的一個十分流行的編程界面,一個Socket由一個IP地址和一個埠號唯一確定。
但是,Socket所支持的協議種類也不光TCP/IP一種,因此兩者之間是沒有必然聯系的。在Java環境下,Socket編程主要是指基於TCP/IP協議的網路編程。

2,Socket通訊的過程
Server端Listen(監聽)某個埠是否有連接請求,Client端向Server 端發出Connect(連接)請求,Server端向Client端發回Accept(接受)消息。一個連接就建立起來了。Server端和Client 端都可以通過Send,Write等方法與對方通信。
對於一個功能齊全的Socket,都要包含以下基本結構,其工作過程包含以下四個基本的步驟:
(1) 創建Socket;
(2) 打開連接到Socket的輸入/出流;
(3) 按照一定的協議對Socket進行讀/寫操作;
(4) 關閉Socket.(在實際應用中,並未使用到顯示的close,雖然很多文章都推薦如此,不過在我的程序中,可能因為程序本身比較簡單,要求不高,所以並未造成什麼影響。)

3,創建Socket
創建Socket
java在包java.net中提供了兩個類Socket和ServerSocket,分別用來表示雙向連接的客戶端和服務端。這是兩個封裝得非常好的類,使用很方便。其構造方法如下:
Socket(InetAddress address, int port);
Socket(InetAddress address, int port, boolean stream);
Socket(String host, int prot);
Socket(String host, int prot, boolean stream);
Socket(SocketImpl impl)
Socket(String host, int port, InetAddress localAddr, int localPort)
Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
ServerSocket(int port);
ServerSocket(int port, int backlog);
ServerSocket(int port, int backlog, InetAddress bindAddr)
其中address、host和port分別是雙向連接中另一方的IP地址、主機名和端 口號,stream指明socket是流socket還是數據報socket,localPort表示本地主機的埠號,localAddr和 bindAddr是本地機器的地址(ServerSocket的主機地址),impl是socket的父類,既可以用來創建serverSocket又可 以用來創建Socket。count則表示服務端所能支持的最大連接數。例如:學習視頻網 http://www.xxspw.com
Socket client = new Socket("127.0.01.", 80);
ServerSocket server = new ServerSocket(80);
注意,在選擇埠時,必須小心。每一個埠提供一種特定的服務,只有給出正確的埠,才 能獲得相應的服務。0~1023的埠號為系統所保留,例如http服務的埠號為80,telnet服務的埠號為21,ftp服務的埠號為23, 所以我們在選擇埠號時,最好選擇一個大於1023的數以防止發生沖突。
在創建socket時如果發生錯誤,將產生IOException,在程序中必須對之作出處理。所以在創建Socket或ServerSocket是必須捕獲或拋出例外。

4,簡單的Client/Server程序
1. 客戶端程序
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);
//向本機的4700埠發出客戶請求
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
//由系統標准輸入設備構造BufferedReader對象
PrintWriter os=new PrintWriter(socket.getOutputStream());
//由Socket對象得到輸出流,並構造PrintWriter對象
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket對象得到輸入流,並構造相應的BufferedReader對象
String readline;
readline=sin.readLine(); //從系統標准輸入讀入一字元串
while(!readline.equals("bye")){
//若從標准輸入讀入的字元串為 "bye"則停止循環
os.println(readline);
//將從系統標准輸入讀入的字元串輸出到Server
os.flush();
//刷新輸出流,使Server馬上收到該字元串
System.out.println("Client:"+readline);
//在系統標准輸出上列印讀入的字元串
System.out.println("Server:"+is.readLine());
//從Server讀入一字元串,並列印到標准輸出上
readline=sin.readLine(); //從系統標准輸入讀入一字元串
} //繼續循環
os.close(); //關閉Socket輸出流
is.close(); //關閉Socket輸入流
socket.close(); //關閉Socket
}catch(Exception e) {
System.out.println("Error"+e); //出錯,則列印出錯信息
}
}
}

2. 伺服器端程序
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);
//創建一個ServerSocket在埠4700監聽客戶請求
}catch(Exception e) {
System.out.println("can not listen to:"+e);
//出錯,列印出錯信息
}
Socket socket=null;
try{
socket=server.accept();
//使用accept()阻塞等待客戶請求,有客戶
//請求到來則產生一個Socket對象,並繼續執行
}catch(Exception e) {
System.out.println("Error."+e);
//出錯,列印出錯信息
}
String line;
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket對象得到輸入流,並構造相應的BufferedReader對象
PrintWriter os=newPrintWriter(socket.getOutputStream());
//由Socket對象得到輸出流,並構造PrintWriter對象
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
//由系統標准輸入設備構造BufferedReader對象
System.out.println("Client:"+is.readLine());
//在標准輸出上列印從客戶端讀入的字元串
line=sin.readLine();
//從標准輸入讀入一字元串
while(!line.equals("bye")){
//如果該字元串為 "bye",則停止循環
os.println(line);
//向客戶端輸出該字元串
os.flush();
//刷新輸出流,使Client馬上收到該字元串
System.out.println("Server:"+line);
//在系統標准輸出上列印讀入的字元串
System.out.println("Client:"+is.readLine());
//從Client讀入一字元串,並列印到標准輸出上
line=sin.readLine();
//從系統標准輸入讀入一字元串
} //繼續循環
os.close(); //關閉Socket輸出流
is.close(); //關閉Socket輸入流
socket.close(); //關閉Socket
server.close(); //關閉ServerSocket
}catch(Exception e){
System.out.println("Error:"+e);
//出錯,列印出錯信息
}
}
}

熱點內容
二級程序編譯答案 發布:2024-05-03 18:41:35 瀏覽:653
領動自動精英版是哪個配置 發布:2024-05-03 18:37:30 瀏覽:150
java編譯器中cd什麼意思 發布:2024-05-03 18:36:00 瀏覽:389
傳奇伺服器如何刷錢 發布:2024-05-03 18:36:00 瀏覽:977
安卓版twitter怎麼注冊 發布:2024-05-03 18:28:05 瀏覽:893
Python邏輯優先順序 發布:2024-05-03 18:26:14 瀏覽:267
linux查看svn密碼 發布:2024-05-03 18:12:47 瀏覽:804
地鐵逃生怎麼進入游戲安卓 發布:2024-05-03 17:49:35 瀏覽:992
aws雲存儲 發布:2024-05-03 17:48:50 瀏覽:955
安卓微信王者號怎麼轉成蘋果 發布:2024-05-03 17:44:38 瀏覽:745