淺談JAVA中如何利用socket進行網(wǎng)絡(luò)編程(二)
Socket是網(wǎng)絡(luò)上運行的兩個程序間雙向通訊的一端,它既可以接受請求,也可以發(fā)送請求,利用它可以較為方便的編寫網(wǎng)絡(luò)上的數(shù)據(jù)的傳遞。在java中,有專門的socket類來處理用戶的請求和響應(yīng)。利用SOCKET類的方法,就可以實現(xiàn)兩臺計算機之間的通訊。這里就介紹一下在JAVA中如何利用socket進行網(wǎng)絡(luò)編程。
接第一篇淺談JAVA中如何利用socket進行網(wǎng)絡(luò)編程(一)
在上一篇中我們已經(jīng)和大家說到客戶端的網(wǎng)絡(luò)編程,下面和大家分享的是服務(wù)器的實現(xiàn)代碼。
- import java.net.*;
- import java.io.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- public class talkServer
- { public static void main(String[] args)
- { try
- { file://建立服務(wù)器
- ServerSocket server = new ServerSocket(9998);
- int i=1;
- for(;;)
- { Socket incoming = server.accept();
- new ServerThread(incoming,i).start();
- i++;
- }
- }catch (IOException ex){
- ex.printStackTrace();
- }
- }
- }
- class ServerThread extends Thread implements ActionListener
- {
- private int threadNum;
- private Socket socket;
- talkServerFrm t;
- BufferedReader in;
- PrintWriter out;
- private boolean talking=true;
- public ServerThread(Socket s,int c)
- { threadNum = c;
- socket = s;
- }
- public void actionPerformed(ActionEvent e)
- { Object source = e.getSource();
- try{
- if(source==t.btnSend)
- { out.println(t.getTalk());
- t.clearTalk();
- }else
- if(source==t.btnEnd)
- { out.println("談話過程被對方終止");
- out.close();
- in.close();
- talking = false;
- }
- }catch(IOException ex){
- }
- }
- public void run()
- { try{
- t=new talkServerFrm(new Integer(threadNum).toString(),this);
- t.setSize(500,500);
- t.show();
- in = new BufferedReader(new
- InputStreamReader(socket.getInputStream()));
- out = new PrintWriter(socket.getOutputStream(),true);
- }catch(Exception e){
- }
- new Thread()
- { public void run()
- { try{
- while(true)
- { checkInput();
- sleep(1000);
- }
- }catch (InterruptedException ex){
- }catch(IOException ex){
- }
- }
- }.start();
- while(talking)
- { }
- t.dispose();
- }
- private void checkInput() throws IOException
- { String line;
- if((line=in.readLine())!=null)
- t.setPartner(line); file://這是界面類里的方法,
- file://用來將line的內(nèi)容輸出到用戶界面
- }
- }
到此,java中的socket網(wǎng)絡(luò)編程就給大家介紹完啦!希望對大家有幫助。
【編輯推薦】