+ All Categories
Home > Documents > Java 網路程式設計 © Copyright 2009 Chia-Hui...

Java 網路程式設計 © Copyright 2009 Chia-Hui...

Date post: 05-Aug-2020
Category:
Upload: others
View: 6 times
Download: 0 times
Share this document with a friend
65
Java 網路程式設計 © Copyright 2009 Chia-Hui Huang Java 網路程式設計 © Copyright 2009 Chia-Hui Huang
Transcript
  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    - 利用 ServerSocket

    public void close()

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Given the name of a host, returns an array of its IP addresses

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Return an IP address for the given host name.

    Returns the IP address string in textual presentation.

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    A new Socket is created !

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Result - Server

    Result - Client

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Class Socket’s

  • Class InputStream

    • InputStream: This abstract class is the superclass of all classes representing an input stream of bytes.

    • Direct Known Subclasses: – AudioInputStream, ByteArrayInputStream, FileInputStream,

    FilterInputStream, ObjectInputStream, piped input stream, SequenceInputStream, StringBufferInputStream

    • public void close() throws IOException: Closes this input stream and releases any system resources associated with the stream.

    Class DataInputStream

    • A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. – An application uses a data output stream to write data that can later

    be read by a data input stream.

    • DataInputStream is not necessarily safe for multithreaded access. Thread safety is optional and is the responsibility of users of methods in this class.

    • public DataInputStream(InputStream in): Creates a DataInputStream that uses the specified underlying InputStream.

  • Example• DataInputStream in;

    DataOutputStream out;ss = new ServerSocket(port);in = new DataInputStream (cs.getInputStream()); out = new DataOutputStream(cs.getOutputStream());

    String outData = "Server Information: " + lineSep +" Local Host: " + ss.getInetAddress().getLocalHost() + lineSep +" Port : " + ss.getLocalPort();byte[] outByte = outData.getBytes();out.write(outByte, 0, outByte.length);out.close();

    Class BufferedReader/BufferedWriter• Reads text from a character-input stream, buffering

    characters so as to provide for the efficient reading of characters, arrays, and lines. – The buffer size may be specified, or the default size may be used.

    The default is large enough for most purposes. • public BufferedReader(Reader in): Creates a buffering

    character-input stream that uses a default-sized input buffer.

    • public BufferedReader(Reader in, int sz)• Programs that use DataInputStreams for textual input can

    be localized by replacing each DataInputStream with an appropriate BufferedReader.

    • public void write(String s, int off, int len) throws IOException

    • public void write(char[] cbuf, int off, int len) throws IOException

    • public void write(int c) throws IOException: Writes a single character.

  • Class BufferedReader• BufferedReader in = new BufferedReader(new

    FileReader("foo.in"))– buffer the input from the specified file.

    Example

    • BufferedReader in;BufferedWriter out;ss = new ServerSocket(port);in = new BufferedReader (new InputStreamReader(ss.getInputStream()));

    out = new BufferedWriter (new OutputStreamWriter(cs.getOutputStream()));String outData = "Server Information: " + lineSep +" Local Host: " +

    ss.getInetAddress().getLocalHost() + lineSep +" Port : " + ss.getLocalPort();out.write(outData, 0, outData.length());out.close();

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Bytes for this operation are read from the contained input stream.

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    •本範例程式Server 端在同一時間僅提供對一個 client 的服務 !!

  • Example• import java.net.*;• import java.io.*;• public class SimpleServer{• ServerSocket ss;• public static void main(String[] args) throws Exception {• int port;• if (args.length == 0) {• System.out.println("Usage: java SimpleServer [port]");• System.exit(1);• }• port = Integer.parseInt(args[0]) ;• SimpleServer server = new SimpleServer(); • server.startServer(port); • }

    ‧ // 建構函式

    ‧ public SimpleServer() {• }• private void startServer(int port) {• try {• ss = new ServerSocket(port);• Thread thread = new Thread(new ClientThread(ss));• thread.start(); • }• catch (IOException ioe) {• ioe.printStackTrace();• }• catch (Exception e) {• e.printStackTrace();• }• }• }

  • ‧ // 執行緒

    • class ClientThread implements Runnable {• private ServerSocket ss;• private Socket cs;• DataInputStream in;• DataOutputStream out;• public ClientThread(ServerSocket ss) throws Exception {• this.ss = ss;• }• public void run() {• try {• while(true) {• cs = ss.accept();

    System.out.println("Connection from • " + cs.getInetAddress().getHostAddress());

    ‧ in = new DataInputStream (cs.getInputStream());• out = new DataOutputStream(cs.getOutputStream());• String lineSep = System.getProperty("line.separator");• InetAddress addr = ss.getInetAddress().getLocalHost() ;• String outData = "Server Information: " + lineSep +• " Local Host: " +

    ss.getInetAddress().getLocalHost() + lineSep +• " Port : " + ss.getLocalPort();• byte[] outByte = outData.getBytes();• out.write(outByte, 0, outByte.length); • out.close();• }• }• catch (Exception ex) {• ex.printStackTrace();• }• }• }

  • SimpleServer• public byte[] getBytes(): Encodes this String into a

    sequence of bytes using the platform's default charset, storing the result into a new byte array.

    • public void write(byte[] b, int off, int len): throws IOExceptionWrites len bytes from the specified byte array starting at offset off to the underlying output stream.

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Example: DateTimeServer

    • import java.net.*;• import java.io.*;• import java.text.*;• public class DateTimeServer {• ServerSocket ss;• public static void main(String[] args) throws Exception {• int port = 13 ;• DateTimeServer server = new DateTimeServer(); • server.startServer(port); • }• public DateTimeServer() {• }

  • • private void startServer(int port) {• try {• ss = new ServerSocket(port);• InetAddress addr = ss.getInetAddress().getLocalHost();• System.out.println("DateTime server started at: " +

    addr.getHostAddress() + ":" + ss.getLocalPort());• System.out.println();• Thread thread = new Thread(new ClientThread(ss));• thread.start();• }• catch (IOException ioe) {• ioe.printStackTrace();• }• catch (Exception e) {• e.printStackTrace();• }• }/* end of startServer */• }

    • class ClientThread implements Runnable {• private ServerSocket ss;• private Socket cs;• public ClientThread(ServerSocket ss) throws Exception {• this.ss = ss;• }• public void run() {• try {• while(true) {• cs = ss.accept();• System.out.println("Connection from " +• cs.getInetAddress().getHostAddress());• DataOutputStream out = new • DataOutputStream(cs.getOutputStream());• String lineSep = System.getProperty("line.separator"); • SimpleDateFormat formatter = new • SimpleDateFormat("yyyy/MM/dd hh:mm aaa");• String date = formatter.format(new java.util.Date());• byte[] outByte = date.getBytes();• out.write(outByte, 0, outByte.length);• out.close();• }/* end of while */• }/* end of try */

  • • catch (Exception ex) {• ex.printStackTrace();• }• }/* end of run */• }/* end of class ClientThread */

    Example: DateTimeServer• [Class Date] public Date(): Allocates a Date object and

    initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

  • Example 3• import java.util.*;• import java.io.*;• import java.net.*;• import java.text.*;• public class Ch931Server{• private static int port = 2468;• private static ArrayList allClient = new ArrayList();• public Ch931Server() throws IOException{• ServerSocket server = new ServerSocket(port);• System.out.println("Server is created,waiting client...");• try{• sendMsg sm = new sendMsg();• sm.start();• while(true){• Socket client = server.accept();• String msg = "Connect from " +

    client.getInetAddress() + " at ";• Date startDateTime=new Date();

    String startTime= DateFormat.getDateInstance().format(startDateTime) + DateFormat.getTimeInstance().format(startDateTime);

    msg += startTime + "\r\n";System.out.print(msg);Client ct= new Client(client,startTime);allClient.add(ct);

    }}catch (IOException e){}finally{

    server.close();}

    }/* end of the Ch931Server constructor */class sendMsg extends Thread{

    private BufferedReader br = null;public sendMsg(){

    br = new BufferedReader(new InputStreamReader(System.in));}

  • public void run(){ try{

    synchronized(this){while(true){

    String msg = br.readLine();if(msg.equals("close")){

    for (int i = 0; i < allClient.size(); i++){Client client = (Client)allClient.get(i); client.close();

    }allClient.clear();

    }else if(msg.equals("dir")){

    for (int i = 0; i < allClient.size(); i++){String ClientMsg = "";Client ct = (Client)allClient.get(i);ClientMsg += getClientMsg(ct);System.out.print(ClientMsg);

    }}

    else{for (int i = 0; i < allClient.size(); i++){

    Client client = (Client)allClient.get(i); //synchronized(client){client.sendMessage(msg); //}

    }/* rnf of for i */}/* end of else */

    }/* end of while */}/* end of sync */

    }catch(IOException ex){}}/* end of run */

  • String getClientMsg(Client ct){Socket client = (Socket)ct.getSocket(); String res = "";res = "IP:" + client.getInetAddress() + ",";res += "Start Time :" + ct.getTime() + "\r\n";return res;

    }}/* end of Ch931Server class */

    class Client{private Socket client;private DataOutputStream outs = null;private String startTime = "";public Client(Socket s,String t) throws IOException{

    client = s;startTime = t;outs = new

    DataOutputStream(client.getOutputStream());outs.writeUTF("Welcome to chatroom!!");outs.flush();

    }public void sendMessage(String msg) throws IOException{

    outs.writeUTF(msg); outs.flush();outs.flush();outs.flush();outs.flush();

    }

  • • public void close() throws IOException{• client.close();• }• //public void run(){allClient.add(this);}• public String getTime(){return startTime;}• public Socket getSocket(){return client;}• }• public static void main(String[] args) throws IOException{• new Ch931Server();• }• }

    21 點遊戲public static void main(String[] args) throws IOException{

    new PokerServer();}public PokerServer() throws IOException{

    ServerSocket server = new ServerSocket(port);try{

    game gm = new game();gm.start();while(true){

    Socket client = server.accept();………ClientThread ct= new ClientThread(client,startTime);ct.start();

    }}catch (IOException e){}finally{

    server.close();}

    }

  • class ClientThread extends Thread{

    private Socket client;private DataOutputStream outs = null;private DataInputStream ins = null;private String startTime = "";private String CName = "";public ArrayList aClientCard = new ArrayList();public ClientThread(Socket s, String t) throws IOException{

    client = s;startTime = t;

    }

    public void run(){

    try{ins = new DataInputStream(client.getInputStream());while (true){

    String clientMsg = ins.readUTF();if (clientMsg.startsWith("name:")){

    CName = clientMsg.substring(clientMsg.indexOf("name:") + 5, clientMsg.length());

    aThreader.add(this);/*Note: private static ArrayList aThreader = new ArrayList();*/

    outs.writeUTF("歡迎" + CName + ",加入遊戲");outs.flush();

    }if (clientMsg.startsWith(“….")){…}

    }/* end of while */}catch (Exception er) { }

    }

  • class game extends Thread{

    public game(){….. }public void run(){

    try{//synchronized(this){while (true){

    String msg = br.readLine();if (msg.equals("start")){

    for (int i = 0; i < aThreader.size(); i++){

    ClientThread ct = (ClientThread)aThreader.get(i);ct.sendMessage("遊戲開始,準備發牌!!");

    }dealFirstTwoCard();

    }/* end of if */

    else if (msg.equals("close")){

    endGame();}else if (…..)){}else if (msg.equals("quit")){

    System.exit(1);}

    }/* end of while */}/* end of try */catch (IOException ex) { }catch (Exception ex) { }

    }/* end of run */}/* end of game */

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    建立用戶端 Socket• public Socket(Proxy proxy): Creates an unconnected

    socket, specifying the type of proxy, if any, that should be used regardless of any other settings. – Proxy type: Direct, HTTP(http/ftp protocol), SOCKS

    • public Proxy(Proxy Type type, SocketAddress sa): Creates an entry representing a PROXY connection. Certain combinations are illegal. For instance, for types Http, and Socks, a SocketAddress must be provided.

    • Socket s = new Socket(Proxy.NO_PROXY) will create a plain socket ignoring any other proxy configuration.

    • Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("socks.mydom.com", 1080))) will create a socket connecting through the specified SOCKS proxy server.

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Methods in Socket• public void bind(SocketAddress bindpoint) throws

    IOException: Binds the socket to a local address. If the address is null, then the system will pick up an ephemeral port and a valid local address to bind the socket.

    • public void close() throws IOException: Closes this socket. Any thread currently blocked in an I/O operation upon this socket will throw a SocketException. Closing this socket will also close the socket's InputStream and OutputStream.

    • public void connect(SocketAddress endpoint) throws IOException: Connects this socket to the server.

    • public void connect(SocketAddress endpoint, int timeout) throws IOException: Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.

  • Methods in Socket• public SocketChannel getChannel(): Returns the unique

    SocketChannel object associated with this socket, if any. • A socket channel may be created and the process of

    establishing the link to the remote socket may be initiated via the connect method for later completion by the finishConnect method.

    • The input and output sides of a socket channel may independently be shut down without actually closing the channel.

    • A socket channel can be connected by invoking its connect() method; once connected, a socket channel remains connected until it is closed.

    • Socket channels support non-blocking connection: A socket channel may be created and the process of establishing the link to the remote socket may be initiated via the connect method for later completion by the finishConnect method.

    Channel

    • InputStream/OutputStream是單向,Channel是雙向。– Stream每次讀寫1byte,Channel每次讀寫「1 chunk of data」– 這「1 chunk of data」指的就是Buffer!– 由Channel進行的I/O,一定都是透過Buffer。

    • 一個 channel 代表一個連到特定裝置的連結(connection),例如file或 a network socket。

    • Channel只有二種狀態, open 或 closed。

  • Socket Channel Methods• Socket channels support asynchronous shutdown.• public abstract boolean connect(SocketAddress remote) throws

    IOException: Connects this channel's socket. – If the connection is established immediately, as can happen with a local

    connection, then this method returns true. Otherwise this method returns false and the connection operation must later be completed by invoking the finishConnect method.

    • public abstract boolean finishConnect() throws IOException: Finishes the process of connecting a socket channel.

    • public static SocketChannel open() throws IOException• public static SocketChannel open(SocketAddress remote)

    throws IOException: Opens a socket channel and connects it to a remote address.

    Socket Channel Methods• public abstract int read(ByteBuffer dst) throws

    IOException: Reads a sequence of bytes from this channel into the given buffer. – Return the number of bytes read, possibly zero, or -1 if the channel

    has reached end-of-stream• public final long read(ByteBuffer [] dsts) throws

    IOException: • public abstract long read(ByteBuffer [] dsts, int offset,

    int length) throws IOException– offset: the offset within the buffer array of the first

    buffer into which bytes are to be transferred; must be non-negative and no larger than dsts.length

    – Length: the maximum number of buffers to be accessed; must be non-negative and no larger than dsts.length - offset

  • Socket Channel Methods• public abstract int write(ByteBuffer src) throws

    IOException: writes a sequence of bytes from this channel into the given buffer. – Return the number of bytes written, possibly zero

    • public final long write(ByteBuffer [] src) throws IOException:

    • public abstract long write(ByteBuffer [] src, int offset, int length) throws IOException

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    public SocketAddress getLocalSocketAddress(): Returns theaddress of the endpoint this socket is bound to, or null if it is notbound yet.

    取得伺服器端的 IP 位址與主機名稱!

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Given the name of a host, returns an array of its IPaddresses

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    public DataInputStream(InputStream in)

    public BufferedReader(Reader in)public BufferedReader(Reader in, int sz)

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

    Java 網路程式設計 © Copyright 2009 Chia-Hui Huang

  • Java 網路程式設計 © Copyright 2009 Chia-Hui Huang


Recommended