NET0183 Networks and Communications: The Socket API
NET0183 Networks and Communications: The Socket API
8/25/2009
8/25/2009
controlled by
application
developer
controlled by
operating
system
process
process
socket
TCP with
buffers,
variables
host or
server
internet
socket
TCP with
buffers,
variables
controlled by
application
developer
controlled by
operating
system
host or
server
sockets/tenglar
2009 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
2009 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
2009 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Figure 3.8 Illustration of the sequence of socket functions called by a client and
server using the stream paradigm.
2009 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
8/25/2009
10
8/25/2009
11
8/25/2009
12
AdditionServer.java
import java.net.*;
import java.io.*;
import javax.swing.*;
13
AdditionServer.java
private void startServer()
{
// declare a "general" socket and a server socket
Socket connection;
ServerSocket listenSocket;
// declare low level and high level objects for input
InputStream inStream;
DataInputStream inDataStream;
// declare low level and high level objects for output
OutputStream outStream;
DataOutputStream outDataStream;
// declare other variables
String client;
int first, second, sum;
boolean connected;
8/25/2009
14
while(true)
AdditionServer.java
{
try {
// create a server socket
listenSocket = new ServerSocket(port);
textWindow.append("Listening on port " + port + "\n");
// listen for a connection from the client
connection = listenSocket.accept ();
connected = true;
// create an input stream from the client
inStream = connection.getInputStream();
inDataStream = new DataInputStream(inStream);
// create an output stream to the client
outStream = connection.getOutputStream ();
outDataStream = new DataOutputStream (outStream );
// wait for a string from the client
client = inDataStream.readUTF();
textWindow.append("Connection established with "
+ client + "\n" );
8/25/2009
15
AdditionServer.java
while(connected)
{
//read an integer from the client
first = inDataStream.readInt();
textWindow.append( "First number received: "
+ first + "\n");
//read an integer from the client
second = inDataStream.readInt();
textWindow.append( "Second number received: "
+ second + "\n");
sum = first + second;
textWindow.append( "Sum returned: "
+ sum + "\n");
//send the sum to the client
outDataStream.writeInt(sum);
}
}
catch (IOException e)
{
connected = false;
}}}}
8/25/2009
16
RunAdditionServer.java
public class RunAdditionServer {
/**
* @param args
*/
public static void main(String[] args) {
new AdditionServer(8901);
}
}
8/25/2009
17
8/25/2009
18