CSCE 790: Computer Network Security

Download Report

Transcript CSCE 790: Computer Network Security

CSCE 515:
Computer Network Programming
Chin-Tser Huang
[email protected]
University of South Carolina
TCP Sockets in Java




Use class Socket and class ServerSocket
An instance of Socket represents one end of a
TCP connection
An instance of ServerSocket listens for client
requests and creates a new Socket instance
to handle each incoming connection
Both client and server use Socket to send and
receive messages
1/22/2004
2
Class Socket
Constructors
Socket(String host, int port) throws IOException
Socket(InetAddress address, int port) throws
IOException
Socket(String host, int port, InetAddress localAddr,
int localPort) throws IOException
Socket(InetAddress address, int port, InetAddress
localAddr, int localPort) throws IOException
1/22/2004
3
Class Socket
Methods
InputStream getInputStream() throws IOException
OutputStream getOutputStream() throws IOException
void close() throws IOException
InetAddress getInetAddress()
int getPort()
InetAddress getLocalAddress()
int getLocalPort()
1/22/2004
4
Class Socket
Methods
void setSoTimeout(int timeout) throws SocketException
int getSoTimeout() throws SocketException
void setTcpNoDelay(boolean on) throws SocketException
boolean getTcpNoDelay() throws SocketException
void setSoLinger(boolean on, int val) throws SocketException
int getSoLinger() throws SocketException
void setSendBufferSize(int size) throws SocketException
int getSendBufferSize() throws SocketException
void setReceiveBufferSize(int size) throws SocketException
int getReceiveBufferSize() throws SocketException
1/22/2004
5
Class Socket
Exceptions
IOException
SocketException
BindException
ConnectException
NoRouteToHostException
SecurityException
1/22/2004
6
A TCP Echo Client Example




Construct a socket with specified server
and port
Communicate with the server using the
socket’s I/O streams
Display the echo from server
Close the connection with server
1/22/2004
7
TCPEchoClient.java
/* * TCP/IP Sockets in Java * Kenneth Calvert, Michael Donahoo *
Morgan Kaufmann Publishers; ISBN 1558606858 * *
http://cs.ecs.baylor.edu/~donahoo/practical/JavaSockets/textco
de.html* * Copyright (c) 2002 Kenneth Calvert, Michael
Donahoo ; * all rights reserved; see license.txt for details. */
import java.net.*;
import java.io.*;
public class TCPEchoClient {
// public static void main (String args[]) …
}
1/22/2004
8
Method main
public static void main(String[] args) throws IOException {
if ((args.length < 2) || (args.length > 3)) // Test for correct # of args
throw new IllegalArgumentException("Parameter(s): <Server> <Word> [<Port>]");
String server = args[0];
// Server name or IP address
// Convert input String to bytes using the default character encoding
byte[] byteBuffer = args[1].getBytes();
int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7;
// Create socket that is connected to server on specified port
Socket socket = new Socket(server, servPort);
System.out.println("Connected to server...sending echo string");
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
…
out.write(byteBuffer); // Send the encoded string to the server
1/22/2004
9
Method main (cont’d)
// Receive the same string back from the server
int totalBytesRcvd = 0; // Total bytes received so far
int bytesRcvd;
// Bytes received in last read
while (totalBytesRcvd < byteBuffer.length) {
if ((bytesRcvd = in.read(byteBuffer, totalBytesRcvd,
byteBuffer.length - totalBytesRcvd)) == -1)
throw new SocketException("Connection close prematurely");
totalBytesRcvd += bytesRcvd;
}
System.out.println("Received: " + new String(byteBuffer));
}
socket.close(); // Close the socket and its streams
1/22/2004
10
Class ServerSocket
Constructors
ServerSocket(int port) throws IOException
ServerSocket(int port, int backlog) throws
IOException
ServerSocket(int port, int backlog, InetAddress
bindAddr) throws IOException
1/22/2004
11
Class ServerSocket
Methods
Socket accept() throws IOException
void close() throws IOException
InetAddress getInetAddress()
int getLocalPort()
Void setSoTimeout(int timeout) throws SocketException
Int getSoTimeout() throws IOException
1/22/2004
12
Class ServerSocket
Exceptions
IOException
SecurityException
1/22/2004
13
A TCP Echo Server Example


Construct a server socket specifying
local port to be listened to
Repeatedly do the following



Accept the next client connection request
and create a socket for this connection
Communicate with the client using the
socket’s I/O streams
Close the connection with client
1/22/2004
14
TCPEchoServer.java
/* * TCP/IP Sockets in Java * Kenneth Calvert, Michael Donahoo *
Morgan Kaufmann Publishers; ISBN 1558606858 * *
http://cs.ecs.baylor.edu/~donahoo/practical/JavaSockets/textco
de.html* * Copyright (c) 2002 Kenneth Calvert, Michael
Donahoo ; * all rights reserved; see license.txt for details. */
import java.net.*;
import java.io.*;
public class TCPEchoServer {
private static final int BUFSIZE = 32; // Size of receive buffer
// public static void main (String args[]) …
}
1/22/2004
15
Method main
public static void main(String[] args) throws IOException {
if (args.length != 1) // Test for correct # of args
throw new IllegalArgumentException("Parameter(s): <Port>");
int servPort = Integer.parseInt(args[0]);
// Create a server socket to accept client connection requests
ServerSocket servSock = new ServerSocket(servPort);
int recvMsgSize; // Size of received message
byte[] byteBuffer = new byte[BUFSIZE]; // Receive buffer
…
1/22/2004
16
Method main (cont’d)
for (;;) { // Run forever, accepting and servicing connections
Socket clntSock = servSock.accept();
// Get client connection
System.out.println("Handling client at " +
clntSock.getInetAddress().getHostAddress() + " on port " +
clntSock.getPort());
InputStream in = clntSock.getInputStream();
OutputStream out = clntSock.getOutputStream();
// Receive until client closes connection, indicated by -1 return
while ((recvMsgSize = in.read(byteBuffer)) != -1)
out.write(byteBuffer, 0, recvMsgSize);
clntSock.close(); // Close the socket. We are done with this client!
}
}
/* NOT REACHED */
1/22/2004
17
Next Class



UDP sockets
Non-blocking
Read JNP Ch. 16, 20
1/22/2004
18