av激情亚洲男人的天堂国语,日韩欧美精品一中文字幕,无码av一区二区三区无码,国产又色又爽又刺激的a片,国产又色又爽又刺激的a片

淺談JAVA中如何利用socket進行網(wǎng)絡編程(二)

Socket是網(wǎng)絡上運行的兩個程序間雙向通訊的一端,它既可以接受請求,也可以發(fā)送請求,利用它可以較為方便的編寫網(wǎng)絡上的數(shù)據(jù)的傳遞。在java中,有專門的socket類來處理用戶的請求和響應。利用SOCKET類的方法,就可以實現(xiàn)兩臺計算機之間的通訊。這里就介紹一下在JAVA中如何利用socket進行網(wǎng)絡編程。

我們提供的服務有:成都網(wǎng)站設計、網(wǎng)站建設、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認證、臺江ssl等。為上千多家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務,是有科學管理、有技術的臺江網(wǎng)站制作公司

接第一篇淺談JAVA中如何利用socket進行網(wǎng)絡編程(一)

在上一篇中我們已經(jīng)和大家說到客戶端的網(wǎng)絡編程,下面和大家分享的是服務器的實現(xiàn)代碼。

 
 
 
  1. import java.net.*;
  2. import java.io.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. public class talkServer
  6. { public static void main(String[] args)
  7.  { try
  8.   { file://建立服務器
  9.    ServerSocket server = new ServerSocket(9998);
  10.    int i=1;
  11.    for(;;)
  12.     { Socket incoming = server.accept();
  13.      new ServerThread(incoming,i).start();
  14.      i++;
  15.     }
  16.    }catch (IOException ex){
  17.    ex.printStackTrace();
  18.   }
  19.  }
  20. }

 
 
 
  1. class ServerThread extends Thread implements ActionListener
  2. {
  3.  private int threadNum;
  4.  private Socket socket;
  5.  talkServerFrm t;
  6.  BufferedReader in;
  7.  PrintWriter out;
  8.  private boolean talking=true;
  9.  public ServerThread(Socket s,int c)
  10.  { threadNum = c;
  11.   socket = s;
  12.  }
 
 
 
  1. public void actionPerformed(ActionEvent e)
  2. { Object source = e.getSource();
  3.  try{
  4.   if(source==t.btnSend)
  5.    { out.println(t.getTalk());
  6.     t.clearTalk();
  7.   }else
  8.   if(source==t.btnEnd)
  9.    { out.println("談話過程被對方終止");
  10.     out.close();
  11.     in.close();
  12.     talking = false;
  13.    }
  14.  }catch(IOException ex){
  15.  }
  16. }
 
 
 
  1. public void run()
  2. { try{
  3.   t=new talkServerFrm(new Integer(threadNum).toString(),this);
  4.   t.setSize(500,500);
  5.   t.show();
  6.   in = new BufferedReader(new 
  7.       InputStreamReader(socket.getInputStream()));
  8.   out = new PrintWriter(socket.getOutputStream(),true);
  9.  }catch(Exception e){
  10. }
  11.  new Thread()
  12.  { public void run()
  13.   { try{
  14.     while(true)
  15.     { checkInput();
  16.      sleep(1000);
  17.   }
  18.  }catch (InterruptedException ex){
  19.  }catch(IOException ex){
  20.  }
  21.  }
  22.  }.start();
  23.  while(talking)
  24.  { }
  25.  t.dispose();
  26.  }
 
 
 
  1. private void checkInput() throws IOException
  2. { String line;
  3.  if((line=in.readLine())!=null)
  4.   t.setPartner(line); file://這是界面類里的方法,
  5.   file://用來將line的內(nèi)容輸出到用戶界面
  6.  }

到此,java中的socket網(wǎng)絡編程就給大家介紹完啦!希望對大家有幫助。


本文名稱:淺談JAVA中如何利用socket進行網(wǎng)絡編程(二)
地址分享:http://uogjgqi.cn/article/dhgpcei.html
掃二維碼與項目經(jīng)理溝通

我們在微信上24小時期待你的聲音

解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯(lián)網(wǎng)交流