SlideShare a Scribd company logo
1 of 5
Download to read offline
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);
}
}
}

More Related Content

Viewers also liked

14. elect digital.ppt
14. elect digital.ppt14. elect digital.ppt
14. elect digital.pptMarcos Rdguez
 
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...Tai Tran
 
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...GEORG Geothermal Workshop 2016
 
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 explorationGEORG Geothermal Workshop 2016
 
SISTEMAS ANALÓGICOS Y DIGITALES
SISTEMAS ANALÓGICOS Y DIGITALESSISTEMAS ANALÓGICOS Y DIGITALES
SISTEMAS ANALÓGICOS Y DIGITALESPEDROASTURES21
 
Direct energy conservation system
Direct energy conservation systemDirect energy conservation system
Direct energy conservation systemBhaskar Choubey
 
Informacion de pagina web
Informacion de pagina webInformacion de pagina web
Informacion de pagina webguitarisk
 

Viewers also liked (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
 

More from 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++
 

Recently uploaded

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 

Recently uploaded (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.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); } } }