Tr - PowerPoint PPT Presentation

1 / 5
About This Presentation
Title:

Tr

Description:

Title: Java sockets (forts) Author: Ellus Brorsson Last modified by: Mikael Nehlsen Created Date: 2/24/1998 10:30:33 PM Document presentation format – PowerPoint PPT presentation

Number of Views:29
Avg rating:3.0/5.0
Slides: 6
Provided by: Ellu7
Category:
Tags: java | threads

less

Transcript and Presenter's Notes

Title: Tr


1
Trådad Echo server
public class ThreadedEchoServer extends Thread
Socket con public static void
main(String args) ... try
ServerSocket ss new ServerSocket(port)
while (true) try
Socket s ss.accept()
ThreadedEchoServer tes new
ThreadedEchoServer(s) tes.start()
catch() ... catch()
...
2
Trådad Echo server (forts)
public ThreadedEchoServer(Socket s) con
s public void run() try
System.out.println("New echo server threaded")
OutputStream os con.getOutputStream()
InputStream is con.getInputStream()
while (true) int n is.read()
if (n -1) break
os.write(n) os.flush()
catch()...
3
Trådar och servers
  • Kostar tid att skapa en ny tråd varje gång man
    får en uppkoppling
  • Lösning Köa socket anropen och lägg upp en pool
    med trådar som kan användas av klienter

4
PoolEchoServer
public class PoolEchoServer extends Thread
public final static int defaultPort 2347
ServerSocket theServer static int num_threads
10 public static void main(String
args) int port defaultPort
... ServerSocket ss new
ServerSocket(port) for (int i 0 i lt
num_threads i) PoolEchoServer pes
new PoolEchoServer(ss) pes.start()
...
5
PoolEchoServer
public PoolEchoServer(ServerSocket ss)
theServer ss public void run()
while (true) try Socket s
theServer.accept() System.out.println("New echo
server threaded") OutputStream os
s.getOutputStream() InputStream is
s.getInputStream() while (true)
int n is.read() if (n -1)
break os.write(n)
os.flush() // end while
// end try catch (IOException e)
// end while // end run
Write a Comment
User Comments (0)
About PowerShow.com