SlideShare una empresa de Scribd logo
1 de 5
Descargar para leer sin conexión
Server socket programming in Java
This program is a server sided program that accepts the clients
requests at a port and socket of the server.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
/**
* The file server program.
*
*/
public class FileServer extends NetCommon {
// the port and socket of the server
private ServerSocket server;
/**
* Create the server socket to accept clients at the given port.
* @param port
*/
public FileServer(int port) throws IOException {
server = new ServerSocket(port);
server.setReuseAddress(true);
System.out.println("The File Server is running at port " +
port);
System.out.println("Press Ctrl-D to terminate.n");
}
/**
* Listen on the specified port and accept clients.
* For each client, a new thread is created to handle it.
*/
public void accept() {
while (true) {
try {
Socket client = server.accept();
InetAddress addr = client.getInetAddress();
System.out.println("Info: new client from " +
addr.getHostName());
// create a new thread to handle this client
new ClientWorker(client);
} catch (IOException e) {
System.out.println("Warning: " + e.getMessage());
}
}
}
// the internal thread class to handle one client.
private class ClientWorker implements Runnable {
final Socket client;
final Thread thread; // the thread instance
final String name; // the name of the client.
public ClientWorker(Socket client) {
this.client = client;
this.name = client.getInetAddress().getHostName();
this.thread = new Thread(this);
this.thread.start();
}
@Override
public void run() {
try {
// get the input and output stream for the client
InputStream input = client.getInputStream();
OutputStream output = client.getOutputStream();
// read the file request from the client
String request = readString(input);
System.out.println("Info: client " + name + "
request: " + request);
// check which type of request it is
String[] fields = request.split("s+");
if (fields.length != 2
|| !Arrays.asList("upload",
"download").contains(fields[0])) {
System.out.println("Warning: could not
understand request: " + request);
} else {
String fileName = fields[1];
if ("upload".equals(fields[0])) {
// try to upload the file, get the
file size.
upload(input, output, fileName);
} else {
// try to download the file
download(input, output, fileName);
}
}
// shutdown the client
client.close();
System.out.println("Info: client " + name + "
closed.");
} catch (IOException e) {
System.out.println(
"Warning: client " + name + " shutdown
unexpectely");
}
}
}
// the client upload the file to the server
private void upload(InputStream input, OutputStream output,
String fileName)
throws IOException
{
// make sure the server can save the file
try {
FileOutputStream fout = new FileOutputStream(new
File(fileName));
// send an OK message to the client
// and read the following bytes from the client to the
file
sendString(output, "OK");
redirect0(input, fout);
fout.close();
} catch (IOException e) {
System.out.println("Warning: could not save into " +
fileName);
// send a FAIL message to the client
sendString(output, "FAIL");
}
}
// the client upload the file to the server
private void download(InputStream input, OutputStream output,
String fileName)
throws IOException
{
// make sure the server can read the file
try {
FileInputStream fin = new FileInputStream(new
File(fileName));
// send an OK message to the client
// and read the following bytes from the client to the
file
sendString(output, "OK");
redirect1(fin, output);
fin.close();
} catch (IOException e) {
System.out.println("Warning: could not read " +
fileName);
// send a FAIL message to the client
sendString(output, "FAIL");
}
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java FileServer <port>");
return;
}
int port = Integer.parseInt(args[0]);
// construct the file server at the given port
try {
new FileServer(port).accept();
} catch (IOException e) {
System.out.println(
"Error: could not start the server at port" +
port);
}
}
}

Más contenido relacionado

Destacado (10)

14. elect digital.ppt
14. elect digital.ppt14. elect digital.ppt
14. elect digital.ppt
 
Los Videojuegos
Los VideojuegosLos Videojuegos
Los Videojuegos
 
Twitter – from Cloning to Localizing for Vietnam Market: A Visual Step-by-ste...
Twitter – from Cloning to Localizing for Vietnam Market: A Visual Step-by-ste...Twitter – from Cloning to Localizing for Vietnam Market: A Visual Step-by-ste...
Twitter – from Cloning to Localizing for Vietnam Market: A Visual Step-by-ste...
 
A3 Sæmundur Ari Halldórsson Volatile systematics of the Iceland hotspot - man...
A3 Sæmundur Ari Halldórsson Volatile systematics of the Iceland hotspot - man...A3 Sæmundur Ari Halldórsson Volatile systematics of the Iceland hotspot - man...
A3 Sæmundur Ari Halldórsson Volatile systematics of the Iceland hotspot - man...
 
C2 Hakkı Aydın
C2 Hakkı AydınC2 Hakkı Aydın
C2 Hakkı Aydın
 
Undertale gk
Undertale gkUndertale gk
Undertale gk
 
B3 Sverrir Þórhallsson Slim wells for geothermal exploration
B3 Sverrir Þórhallsson Slim wells for geothermal explorationB3 Sverrir Þórhallsson Slim wells for geothermal exploration
B3 Sverrir Þórhallsson Slim wells for geothermal exploration
 
SISTEMAS ANALÓGICOS Y DIGITALES
SISTEMAS ANALÓGICOS Y DIGITALESSISTEMAS ANALÓGICOS Y DIGITALES
SISTEMAS ANALÓGICOS Y DIGITALES
 
Direct energy conservation system
Direct energy conservation systemDirect energy conservation system
Direct energy conservation system
 
Informacion de pagina web
Informacion de pagina webInformacion de pagina web
Informacion de pagina web
 

Más de Programming Homework Help

Más de Programming Homework Help (9)

Java Assignment Help
Java  Assignment  HelpJava  Assignment  Help
Java Assignment Help
 
C# Assignmet Help
C# Assignmet HelpC# Assignmet Help
C# Assignmet Help
 
C# Assignmet Help
C# Assignmet HelpC# Assignmet Help
C# Assignmet Help
 
Family tree in java
Family tree in javaFamily tree in java
Family tree in java
 
Binary tree in java
Binary tree in javaBinary tree in java
Binary tree in java
 
Bank account in java
Bank account in javaBank account in java
Bank account in java
 
Mouse and Cat Game In C++
Mouse and Cat Game In C++Mouse and Cat Game In C++
Mouse and Cat Game In C++
 
Word games in c
Word games in cWord games in c
Word games in c
 
Card Games in C++
Card Games in C++Card Games in C++
Card Games in C++
 

Último

Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 

Último (20)

Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 

Java Assignment Help

  • 1.
  • 2. Server socket programming in Java This program is a server sided program that accepts the clients requests at a port and socket of the server. import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.Arrays; /** * The file server program. * */ public class FileServer extends NetCommon { // the port and socket of the server private ServerSocket server; /** * Create the server socket to accept clients at the given port. * @param port */ public FileServer(int port) throws IOException { server = new ServerSocket(port); server.setReuseAddress(true); System.out.println("The File Server is running at port " + port); System.out.println("Press Ctrl-D to terminate.n"); } /** * Listen on the specified port and accept clients. * For each client, a new thread is created to handle it. */ public void accept() { while (true) { try { Socket client = server.accept(); InetAddress addr = client.getInetAddress(); System.out.println("Info: new client from " + addr.getHostName());
  • 3. // create a new thread to handle this client new ClientWorker(client); } catch (IOException e) { System.out.println("Warning: " + e.getMessage()); } } } // the internal thread class to handle one client. private class ClientWorker implements Runnable { final Socket client; final Thread thread; // the thread instance final String name; // the name of the client. public ClientWorker(Socket client) { this.client = client; this.name = client.getInetAddress().getHostName(); this.thread = new Thread(this); this.thread.start(); } @Override public void run() { try { // get the input and output stream for the client InputStream input = client.getInputStream(); OutputStream output = client.getOutputStream(); // read the file request from the client String request = readString(input); System.out.println("Info: client " + name + " request: " + request); // check which type of request it is String[] fields = request.split("s+"); if (fields.length != 2 || !Arrays.asList("upload", "download").contains(fields[0])) { System.out.println("Warning: could not understand request: " + request); } else { String fileName = fields[1]; if ("upload".equals(fields[0])) { // try to upload the file, get the file size. upload(input, output, fileName); } else {
  • 4. // try to download the file download(input, output, fileName); } } // shutdown the client client.close(); System.out.println("Info: client " + name + " closed."); } catch (IOException e) { System.out.println( "Warning: client " + name + " shutdown unexpectely"); } } } // the client upload the file to the server private void upload(InputStream input, OutputStream output, String fileName) throws IOException { // make sure the server can save the file try { FileOutputStream fout = new FileOutputStream(new File(fileName)); // send an OK message to the client // and read the following bytes from the client to the file sendString(output, "OK"); redirect0(input, fout); fout.close(); } catch (IOException e) { System.out.println("Warning: could not save into " + fileName); // send a FAIL message to the client sendString(output, "FAIL"); } } // the client upload the file to the server private void download(InputStream input, OutputStream output, String fileName) throws IOException { // make sure the server can read the file try { FileInputStream fin = new FileInputStream(new File(fileName)); // send an OK message to the client // and read the following bytes from the client to the file sendString(output, "OK");
  • 5. redirect1(fin, output); fin.close(); } catch (IOException e) { System.out.println("Warning: could not read " + fileName); // send a FAIL message to the client sendString(output, "FAIL"); } } public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: java FileServer <port>"); return; } int port = Integer.parseInt(args[0]); // construct the file server at the given port try { new FileServer(port).accept(); } catch (IOException e) { System.out.println( "Error: could not start the server at port" + port); } } }