A. java編程中,Socket通信是怎麼實現的
java編程對於Socket之間的通信過程如下:
服務端往Socket的輸出流裡面寫東西,客戶端就可以通過Socket的輸入流讀取對應的內容。Socket與Socket之間是雙向連通的,所以客戶端也可以往對應的Socket輸出流裡面寫東西,然後服務端對應的Socket的輸入流就可以讀出對應的內容。下面來看一些服務端與客戶端通信的例子:
publicclassServer{
publicstaticvoidmain(Stringargs[])throwsIOException{
//為了簡單起見,所有的異常信息都往外拋
intport=8899;
//定義一個ServerSocket監聽在埠8899上
ServerSocketserver=newServerSocket(port);
//server嘗試接收其他Socket的連接請求,server的accept方法是阻塞式的
Socketsocket=server.accept();
//跟客戶端建立好連接之後,我們就可以獲取socket的InputStream,並從中讀取客戶端發過來的信息了。
Readerreader=newInputStreamReader(socket.getInputStream());
charchars[]=newchar[64];
intlen;
StringBuildersb=newStringBuilder();
while((len=reader.read(chars))!=-1){
sb.append(newString(chars,0,len));
}
System.out.println("fromclient:"+sb);
reader.close();
socket.close();
server.close();
}
}客戶端代碼
Java代碼publicclassClient{
publicstaticvoidmain(Stringargs[])throwsException{
//為了簡單起見,所有的異常都直接往外拋
Stringhost="127.0.0.1";//要連接的服務端IP地址
intport=8899;//要連接的服務端對應的監聽埠
//與服務端建立連接
Socketclient=newSocket(host,port);
//建立連接後就可以往服務端寫數據了
Writerwriter=newOutputStreamWriter(client.getOutputStream());
writer.write("HelloServer.");
writer.flush();//寫完後要記得flush
writer.close();
client.close();
}
}
B. java socket輸入流inputStream.read(byte[])方法一次讀入多幀數據,也就是多幀數據連在一起
因為inputStream.read(byte)是盡可抄能的讀byte[]大小的數據襲,當你的服務端發送數據速度大於客戶端讀取數據的速度時,就會出現客戶端讀到多幀連在一起的報文。而這些發送數據,讀取數據的速度是未知的。所以我們需要人為的來做一些調整。比如說每一幀作為一行寫入Socket,客戶端每次從socket讀取一行。這樣客戶端每次都是讀取一幀。
以上情況可以這樣實現:在服務端使用PrintWriter
PrintWriterwriter=newPrintWriter(socket.getOutputStream());
writer.println(data);
客戶端可以使用BufferedReader
BufferedReaderreader=newBufferedReader(newBufferedInputStream(socket.getInputStream()));
Strings=reader.readLine();
C. 怎麼用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實用教程上的.
D. java的serversocket怎麼接受來自客戶端的數據
通過accept()獲取Socket,然後獲取IO流,這個是我寫的從客戶端下載文件的客戶端代碼,代碼如下
ServerSocketserverSocket=newServerSocket(10002);
while(true){
Socketsocket=serverSocket.accept();
OutputStreamOutput=socket.getOutputStream();
FileInputStreaminput=newFileInputStream("F:\Play.mp4");
byte[]buf=newbyte[1024];
intlength=0;
while((length=input.read(buf))!=-1){
Output.write(buf,0,length);
}
Stringip=socket.getInetAddress().getHostAddress();
System.out.println(ip);
input.close();
socket.close();
}
E. java socket編程 readline()讀取問題,為啥在client端剛連接上就開始無限循環,停不下來
改一下
scan.nextLine();//阻塞,排除是socket建立太慢導致的
String str=null;
這兩行刪除,沒用
str=br.readLine();
這個改成
br=scan.readLine();
然後你再試一下
順便再說一下,這個程序我寫過,我開始想的也是客戶端發送的數據伺服器端可以實時接收,但是我發現我錯了,因為Scanner 的阻塞,如果客戶端發送消息伺服器端必須也得發送一個消息才能收到,這個內容可以是任意內容,比如一個回車,如果想讓客戶端 或伺服器端可以實時接收到消息,在控制台中是不可能實現的,除非使用swing框架,一個文本框負負責發送,一個文本框負責接收,不過聽他們說swing現在企業中根本不用了,所有我也就沒有深入研究,勸你也放棄吧,研究這個沒什麼用,除非你能在網頁上實現,或者做一個程序,至於我寫的源碼,如果你要我可以發給你
對了再說下你這個問題出現的原因
你這個是因為循環中沒有阻塞語句,而且br沒有接收到值,所有它會一直列印null
F. 用JAVA SOCKET編程,讀伺服器幾個字元,再寫入本地顯示怎麼寫
答:Server端程序: package test; import java.net.*; import java.io.*; public class Server { private ServerSocket ss; private Socket socket; private BufferedReader in; private PrintWriter out; public Server() { try { ss=new ServerSocket(10000); while(true) { socket = ss.accept(); String RemoteIP = socket.getInetAddress().getHostAddress(); String RemotePort = ":"+socket.getLocalPort(); System.out.println("A client come in!IP:"+RemoteIP+RemotePort); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line = in.readLine(); System.out.println("Cleint send is :" + line); out = new PrintWriter(socket.getOutputStream(),true); out.println("Your Message Received!"); out.close(); in.close(); socket.close(); } }catch (IOException e) { out.println("wrong"); } } public static void main(String[] args)
G. java socket多文件傳輸問題
參考思路:
1.先傳文件名跟文件大小到 server。
2.開始傳文件。
3.告訴server傳完了。
4.客戶端開始傳下一個,重復123。
參考簡單代碼:
long fileLength;
int readLength;
long totalLength;
for (...)
{
 
   // 讀取文件名
   // 讀取文件長度保存到fileLength中
   // 將totalLength置為0
   while (1)
   {
      // 讀取數據流,將實際讀取的位元組數保存在readLength中
      totalLength += readLength;
       
      if (totalLength >= fileLength) // 一個文件讀取完成,break
      // 這樣就差不多了,不過這會把下一個文件的信息讀到當前文件中來。
      // 思路是fileLength - totalLength小於等於你設置的緩沖區長度時讀取長度就是fileLength - totalLength
   }
    
}
H. java中socket不斷接收數據問題
其實,方法有幾個。
方法一:
定義一個MsgObject的消息類,裡面存放的為發送的消息內容(專記得序列化)。屬然後再用ObjectOutputStream來把該類弄成一個輸出流發送出去。然後客戶端就用
ObjectInputStream in=new ObjectInputStream(socket.getInputStream());
MsgObject obj=(MsgObject)in.getObject();就能夠得到一個消息類對象了。。
不會的就追問下,我之前是這樣做過的。
方法二:
如果你會json格式,那麼就更加簡單了,直接把你的消息放到json數組裡面。。
這種方法沒試過,我近期使用json過於頻繁才突然記得的,如果你有興趣用這個方法,可以一起討論下。
方法三:
弄多個輸入輸出流,但是這個不建議