JWorld@TW the best professional Java site in Taiwan
      註冊 | 登入 | 全文檢索 | 排行榜  

» JWorld@TW » Java 程式分享區  

按列印兼容模式列印這個話題 列印話題    把這個話題寄給朋友 寄給朋友    訂閱主題
reply to postflat modego to previous topicgo to next topic
本主題所含的標籤
無標籤
作者 ServerSocket 的簡單範例, Simple Demo for Server Socket, Client Socket
bernardvai





發文: 491
積分: 0
於 2007-07-04 20:49 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
自己寫下的範例, 分享給各位網友.
功能齊備, 可Multi-Client, 及可以偵測 Client Disconnect.

SocketServer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.io.*;
import java.net.*;
import java.util.*;
 
public class SocketServer {
   public static Vector v = new Vector();   
   public static void main(String[] args ){  
   int i = 1;
      try {  
         ServerSocket s = new ServerSocket(8189);
 
         for (;;) {  
            Socket incoming = s.accept( );
            System.out.println("ID : " + i+ ", Connection Started");
            new SocketServer_Thread(incoming, i,v).start();
            i++;
         }
      } catch (Exception e) {  
         System.out.println("Exception in line 19 : "+e);
      }
   }
}
 
class SocketServer_Thread extends Thread {
    private Socket incoming;
    private int counter;
    private Vector v;    
    private String name = "Unknown";
    public SocketServer_Thread(Socket i, int c, Vector v) {
        incoming = i; counter = c; this.v = v ;        
    } 
    public void connectionEnded(){        
        //v.remove(thisincoming);
        v.remove(this);
        System.out.println("ID : " + counter+ ", Connection Ended");
    }
 
    public void run(){
    try { 
        BufferedReader in = new BufferedReader
            (new InputStreamReader(incoming.getInputStream()));
        PrintWriter out = new PrintWriter
            (incoming.getOutputStream(), true /* autoFlush */);
 
        out.println( "Enter BYE to exit." ); 
        out.println( "Enter name:xxxx to set your name" );        
        //v.add(incoming);
        v.add(this);
        boolean done = false;
        while (!done) {  
            String str = in.readLine();
            if (str == null) {
                done = true;
            } else {
                if (str.trim().equals("BYE")) {
                   done = true;                          
                } else if (str.startsWith("name:")) {
                   name = str.substring(5);
                   out.println("Your name set to "+name);                   
                } else {
                    PrintWriter tempOut ;
                    System.out.println("Current clients = "+v.size());
                    String sendTo = "";
                    if (str.startsWith("to ") && str.indexOf(":")>=0 ) {
                      sendTo = str.substring(3,str.indexOf(":"));
                      str = str.substring(str.indexOf(":")+1);
                    }
                    for (Enumeration e = v.elements(); e.hasMoreElements(); ) {
                        //Socket tempSocket = (Socket) e.nextElement();      
               SocketServer_Thread tempThread = (SocketServer_Thread) e.nextElement();
               if (sendTo.equals("") || tempThread.name.equals(sendTo)) {               
                 Socket tempSocket = tempThread.incoming;
                          try {
                              tempOut = new PrintWriter
                              (tempSocket.getOutputStream(), true /* autoFlush */);
                              tempOut.println(name +":" + str);
                          } catch (Exception ex) {
                              System.out.println("Exception in line 78 : "+ex);                            
                          }
                        }
                    }                        
                }                
            }
         }
         incoming.close();
      } catch (Exception e) {           
         System.out.println("Exception in line 87 : "+e);         
      }
      connectionEnded();
   }   
}


SocketClient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.io.*;
import java.util.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
 
public class SocketClient{  
    public static BufferedReader in;
    public static PrintWriter out;
    public static TextField jtf;
    public static void main(String[] args){  
      JFrame f = new JFrame("Socket Client");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container c = f.getContentPane();
      c.setLayout(new BorderLayout());        
      f.setLocation(300,300);
      f.setSize(500,300);      
        TextArea jta = new TextArea(5,30);
        jta.setFocusable(false);
      //jta.setEnabled(false);
      jta.setFont(new Font("Arial",0,20));      
      jtf = new TextField("");      
        jtf.setFont (new Font("Arial",0,20));
      c.add("Center",jta);
      c.add("South",jtf);              
        jtf.addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent e) {                
                if (e.getKeyCode() == 10){
                   out.println(jtf.getText());                   
                   jtf.setText("");
                }
            }
            public void keyReleased(KeyEvent e) {}
            public void keyTyped(KeyEvent e) {} 
        });
        f.setVisible(true);
      try {
          Socket s = new Socket("127.0.0.1",8189);
          in = new BufferedReader (new InputStreamReader(s.getInputStream()));
          out = new PrintWriter(s.getOutputStream(), true);
          boolean more = true;
          while(more) {
              String inStr = in.readLine();
              if (inStr == null) {
                  more = false;
              } else {
                  jta.append(""+inStr+"\n");
              }    
          }
      } catch (IOException e) {
            jta.append("Exception in line 52 : " + e);
        }
        
    }
}
 


bernardvai edited on 2007-07-04 20:51
reply to postreply to post
話題樹型展開
人氣 標題 作者 字數 發文時間
8921 ServerSocket 的簡單範例, Simple Demo for Server Socket, Client Socket bernardvai 5603 2007-07-04 20:49
4631 Re:ServerSocket 的簡單範例, Simple Demo for Server Socket, Client Socket linshengte 75 2007-07-05 16:09
» JWorld@TW »  Java 程式分享區

reply to postflat modego to previous topicgo to next topic
  已讀文章
  新的文章
  被刪除的文章
Jump to the top of page

JWorld@TW 本站商標資訊

Powered by Powerful JuteForum® Version Jute 1.5.8