001: /*
002: * SocketChannel.java
003: *
004: * Implements a socket channel.
005: */
006: package tcl.lang;
007:
008: import java.io.*;
009: import java.net.Socket;
010: import java.net.InetAddress;
011: import java.net.UnknownHostException;
012:
013: /**
014: * The SocketChannel class implements a channel object for Socket
015: * connections, created using the socket command.
016: **/
017:
018: public class SocketChannel extends Channel {
019:
020: /**
021: * The java Socket object associated with this Channel
022: **/
023:
024: private Socket sock;
025:
026: /**
027: * Constructor - creates a new SocketChannel object with the given
028: * options. Also creates an underlying Socket object, and Input and
029: * Output Streams.
030: **/
031:
032: public SocketChannel(Interp interp, int mode, String localAddr,
033: int localPort, boolean async, String address, int port)
034: throws IOException, TclException {
035: InetAddress localAddress = null;
036: InetAddress addr = null;
037:
038: if (async)
039: throw new TclException(interp,
040: "Asynchronous socket connection not "
041: + "currently implemented");
042:
043: // Resolve addresses
044: if (!localAddr.equals("")) {
045: try {
046: localAddress = InetAddress.getByName(localAddr);
047: } catch (UnknownHostException e) {
048: throw new TclException(interp, "host unknown: "
049: + localAddr);
050: }
051: }
052:
053: try {
054: addr = InetAddress.getByName(address);
055: } catch (UnknownHostException e) {
056: throw new TclException(interp, "host unknown: " + address);
057: }
058:
059: // Set the mode of this socket.
060: this .mode = mode;
061:
062: // Create the Socket object
063:
064: if ((localAddress != null) && (localPort != 0))
065: sock = new Socket(addr, port, localAddress, localPort);
066: else
067: sock = new Socket(addr, port);
068:
069: // If we got this far, then the socket has been created.
070: // Create the channel name
071: setChanName(TclIO.getNextDescriptor(interp, "sock"));
072: }
073:
074: /**
075: * Constructor for making SocketChannel objects from connections
076: * made to a ServerSocket.
077: **/
078:
079: public SocketChannel(Interp interp, Socket s) throws IOException,
080: TclException {
081: this .mode = TclIO.RDWR;
082: this .sock = s;
083:
084: setChanName(TclIO.getNextDescriptor(interp, "sock"));
085: }
086:
087: /**
088: * Close the SocketChannel.
089: */
090:
091: void close() throws IOException {
092: // Invoke super.close() first since it might write an eof char
093: try {
094: super .close();
095: } finally {
096: sock.close();
097: }
098: }
099:
100: String getChanType() {
101: return "tcp";
102: }
103:
104: protected InputStream getInputStream() throws IOException {
105: return sock.getInputStream();
106: }
107:
108: protected OutputStream getOutputStream() throws IOException {
109: return sock.getOutputStream();
110: }
111: }
|