Java/Network Protocol/Socket
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 A simple network client that establishes a network connection to a specified port on a specified host, send an optional message across the connection
- 2 A timeout feature on socket connections
- 3 Connects to a server at a specified host and port. It reads text from the console and sends it to the server
- 4 Create a socket with a timeout
- 5 Create a socket without a timeout
- 6 Create PrintWriter from BufferedWriter, OutputStreamWriter and Socket
- 7 deleting messages from a POP3 mailbox based on message size and Subject line
- 8 Demonstrate Sockets.
- 9 Download WWW Page
- 10 Get email with Socket
- 11 Get the Date from server
- 12 ObjectInputStream and ObjectOutputStream from Socket
- 13 Ping a server
- 14 Read and write through socket
- 15 Read float number from a Socket
- 16 Read from server
- 17 Reading Text from a Socket
- 18 Read Object from Socket
- 19 Redirects incoming TCP connections to other hosts/ports
- 20 Sending a POST Request Using a Socket
- 21 ServerSocket and Socket for Serializable object
- 22 Socket Address Encoder
- 23 Socket connection and concurrent package
- 24 Socket Fetcher
- 25 String based communication between Socket
- 26 Transfer a file via Socket
- 27 Use Socket to read and write stream
- 28 Write Double Using Sockets
- 29 Write Objects From Socket
- 30 Writing Text to a Socket
- 31 XML based message
- 32 Zip socket
A simple network client that establishes a network connection to a specified port on a specified host, send an optional message across the connection
/*
* Copyright (c) 2004 David Flanagan. All rights reserved.
* This code is from the book Java Examples in a Nutshell, 3nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose,
* including teaching and use in open-source projects.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book,
* please visit http://www.davidflanagan.ru/javaexamples3.
*/
//package je3.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketTimeoutException;
/**
* A simple network client that establishes a network connection to a specified
* port on a specified host, send an optional message across the connection,
* reads the response from the server and exits. A suitable client for simple
* network services like the daytime or finger.
*/
public class Connect {
public static void main(String[] args) {
try { // Handle exceptions below
// Get our command-line arguments
String hostname = args[0];
int port = Integer.parseInt(args[1]);
String message = "";
if (args.length > 2)
for (int i = 2; i < args.length; i++)
message += args[i] + " ";
// Create a Socket connected to the specified host and port.
Socket s = new Socket(hostname, port);
// Get the socket output stream and wrap a PrintWriter around it
PrintWriter out = new PrintWriter(s.getOutputStream());
// Sent the specified message through the socket to the server.
out.print(message + "\r\n");
out.flush(); // Send it now.
// Get an input stream from the socket and wrap a BufferedReader
// around it, so we can read lines of text from the server.
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
// Before we start reading the server"s response tell the socket
// that we don"t want to wait more than 3 seconds
s.setSoTimeout(3000);
// Now read lines from the server until the server closes the
// connection (and we get a null return indicating EOF) or until
// the server is silent for 3 seconds.
try {
String line;
while ((line = in.readLine()) != null)
// If we get a line
System.out.println(line); // print it out.
} catch (SocketTimeoutException e) {
// We end up here if readLine() times out.
System.err.println("Timeout; no response from server.");
}
out.close(); // Close the output stream
in.close(); // Close the input stream
s.close(); // Close the socket
} catch (IOException e) { // Handle IO and network exceptions here
System.err.println(e);
} catch (NumberFormatException e) { // Bad port number
System.err.println("You must specify the port as a number");
} catch (ArrayIndexOutOfBoundsException e) { // wrong # of args
System.err.println("Usage: Connect <hostname> <port> message...");
}
}
}
A timeout feature on socket connections
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.Socket;
/**
* This class offers a timeout feature on socket connections.
* A maximum length of time allowed for a connection can be
* specified, along with a host and port.
*
* @author David Reilly (written for JavaWorld)
* @author Daniel Matuschek
* @version $Id: TimedSocket.java,v 1.2 2002/05/31 14:45:56 matuschd Exp $
*
* imported to the net.matuschek.util source tree by Daniel Matuschek
*/
public class TimedSocket
{
/**
* Attempts to connect to a service at the specified address
* and port, for a specified maximum amount of time.
*
* @param addr Address of host
* @param port Port of service
* @param delay Delay in milliseconds
*/
public static Socket getSocket ( InetAddress addr, int port, int delay)
throws InterruptedIOException, IOException
{
// Create a new socket thread, and start it running
SocketThread st = new SocketThread( addr, port );
st.start();
int timer = 0;
Socket sock = null;
for (;;) {
// Check to see if a connection is established
if (st.isConnected()) {
// Yes ... assign to sock variable, and break out of loop
sock = st.getSocket();
break;
} else {
// Check to see if an error occurred
if (st.isError()) {
// No connection could be established
throw (st.getException());
}
try {
// Sleep for a short period of time
Thread.sleep ( POLL_DELAY );
} catch (InterruptedException ie) {}
// Increment timer
timer += POLL_DELAY;
// Check to see if time limit exceeded
if (timer > delay) {
// Can"t connect to server
throw new InterruptedIOException("Could not connect for " +
delay + " milliseconds");
}
}
}
return sock;
}
/**
* Attempts to connect to a service at the specified address
* and port, for a specified maximum amount of time.
*
* @param host Hostname of machine
* @param port Port of service
* @param delay Delay in milliseconds
*/
public static Socket getSocket ( String host, int port, int delay)
throws InterruptedIOException, IOException
{
// Convert host into an InetAddress, and call getSocket method
InetAddress inetAddr = InetAddress.getByName (host);
return getSocket ( inetAddr, port, delay );
}
/**
* Inner class for establishing a socket thread
* within another thread, to prevent blocking.
*/
static class SocketThread extends Thread
{
// Socket connection to remote host
volatile private Socket m_connection = null;
// Hostname to connect to
private String m_host = null;
// Internet Address to connect to
private InetAddress m_inet = null;
// Port number to connect to
private int m_port = 0;
// Exception in the event a connection error occurs
private IOException m_exception = null;
// Connect to the specified host and port number
public SocketThread ( String host, int port) {
// Assign to member variables
m_host = host;
m_port = port;
}
// Connect to the specified host IP and port number
public SocketThread ( InetAddress inetAddr, int port ) {
// Assign to member variables
m_inet = inetAddr;
m_port = port;
}
public void run() {
// Socket used for establishing a connection
Socket sock = null;
try {
// Was a string or an inet specified
if (m_host != null) {
// Connect to a remote host - BLOCKING I/O
sock = new Socket (m_host, m_port);
} else {
// Connect to a remote host - BLOCKING I/O
sock = new Socket (m_inet, m_port);
}
}
catch (IOException ioe) {
// Assign to our exception member variable
m_exception = ioe;
return;
}
// If socket constructor returned without error,
// then connection finished
m_connection = sock;
}
// Are we connected?
public boolean isConnected() {
if (m_connection == null)
return false;
else
return true;
}
// Did an error occur?
public boolean isError() {
if (m_exception == null)
return false;
else
return true;
}
// Get socket
public Socket getSocket() {
return m_connection;
}
// Get exception
public IOException getException() {
return m_exception;
}
}
/** Polling delay for socket checks (in milliseconds) */
private static final int POLL_DELAY = 100;
}
Connects to a server at a specified host and port. It reads text from the console and sends it to the server
/*
* Copyright (c) 2004 David Flanagan. All rights reserved.
* This code is from the book Java Examples in a Nutshell, 3nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose,
* including teaching and use in open-source projects.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book,
* please visit http://www.davidflanagan.ru/javaexamples3.
*/
//package je3.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.Socket;
/**
* This program connects to a server at a specified host and port. It reads text
* from the console and sends it to the server. It reads text from the server
* and sends it to the console.
*/
public class GenericClient {
public static void main(String[] args) throws IOException {
try {
// Check the number of arguments
if (args.length != 2)
throw new IllegalArgumentException("Wrong number of args");
// Parse the host and port specifications
String host = args[0];
int port = Integer.parseInt(args[1]);
// Connect to the specified host and port
Socket s = new Socket(host, port);
// Set up streams for reading from and writing to the server.
// The from_server stream is final for use in the inner class below
final Reader from_server = new InputStreamReader(s.getInputStream());
PrintWriter to_server = new PrintWriter(s.getOutputStream());
// Set up streams for reading from and writing to the console
// The to_user stream is final for use in the anonymous class below
BufferedReader from_user = new BufferedReader(new InputStreamReader(System.in));
// Pass true for auto-flush on println()
final PrintWriter to_user = new PrintWriter(System.out, true);
// Tell the user that we"ve connected
to_user.println("Connected to " + s.getInetAddress() + ":" + s.getPort());
// Create a thread that gets output from the server and displays
// it to the user. We use a separate thread for this so that we
// can receive asynchronous output
Thread t = new Thread() {
public void run() {
char[] buffer = new char[1024];
int chars_read;
try {
// Read characters from the server until the
// stream closes, and write them to the console
while ((chars_read = from_server.read(buffer)) != -1) {
to_user.write(buffer, 0, chars_read);
to_user.flush();
}
} catch (IOException e) {
to_user.println(e);
}
// When the server closes the connection, the loop above
// will end. Tell the user what happened, and call
// System.exit(), causing the main thread to exit along
// with this one.
to_user.println("Connection closed by server.");
System.exit(0);
}
};
// Now start the server-to-user thread
t.start();
// In parallel, read the user"s input and pass it on to the server.
String line;
while ((line = from_user.readLine()) != null) {
to_server.print(line + "\r\n");
to_server.flush();
}
// If the user types a Ctrl-D (Unix) or Ctrl-Z (Windows) to end
// their input, we"ll get an EOF, and the loop above will exit.
// When this happens, we stop the server-to-user thread and close
// the socket.
s.close();
to_user.println("Connection closed by client.");
System.exit(0);
}
// If anything goes wrong, print an error message
catch (Exception e) {
System.err.println(e);
System.err.println("Usage: java GenericClient <hostname> <port>");
}
}
}
Create a socket with a timeout
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
public class Main {
public static void main(String[] argv) throws Exception {
InetAddress addr = InetAddress.getByName("java.sun.ru");
int port = 80;
SocketAddress sockaddr = new InetSocketAddress(addr, port);
Socket sock = new Socket();
int timeoutMs = 2000;
sock.connect(sockaddr, timeoutMs);
}
}
Create a socket without a timeout
import java.net.InetAddress;
import java.net.Socket;
public class Main {
public static void main(String[] argv) throws Exception {
InetAddress addr = InetAddress.getByName("java.sun.ru");
int port = 80;
Socket socket = new Socket(addr, port);
}
}
Create PrintWriter from BufferedWriter, OutputStreamWriter and Socket
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class Main {
public static void main(String[] arges) throws Exception {
InetAddress addr = InetAddress.getByName(null);
Socket sk = new Socket(addr, 8888);
BufferedReader in = new BufferedReader(new InputStreamReader(sk.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())), true);
out.println("asdf");
System.out.println(in.readLine());
}
}
deleting messages from a POP3 mailbox based on message size and Subject line
/*
* Copyright (c) 2004 David Flanagan. All rights reserved.
* This code is from the book Java Examples in a Nutshell, 3nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose,
* including teaching and use in open-source projects.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book,
* please visit http://www.davidflanagan.ru/javaexamples3.
*/
//package je3.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A simple utility program for deleting messages from a POP3 mailbox based on
* message size and Subject line. Don"t run this program unless you understand
* what it is doing. It deletes e-mail without downloading it: YOU MAY
* PERMANENTLY LOSE DATA!
*
* Typical usage: 1) Look at the subject lines for the big messages you"ve got
* java PopClean -host host -user user -pass pass -size 100000
*
* 2) Create a regular expression to match viral subject lines, and use it to
* delete large matching messages java PopClean -host h -user u -pass p -delete
* -size 100000 \ -subject "Thank you!|Re: Your application" This will ask for
* confirmation before proceeding.
*
* 3) If you"re confident that all big messages are virus-infected, then you can
* skip the -subject argument and delete on size alone java PopClean -host h
* -user u -pass p -delete -size 100000 This will ask for confirmation before
* proceeding.
*/
public class PopClean {
static Socket s = null; // The connection to the server
static BufferedReader in = null; // To read lines from the server
static PrintWriter out = null; // To write to the server
static boolean debug = false; // Are we in debug mode?
public static void main(String args[]) {
try {
String hostname = null, username = null, password = null;
int port = 110;
int sizelimit = -1;
String subjectPattern = null;
Pattern pattern = null;
Matcher matcher = null;
boolean delete = false;
boolean confirm = true;
// Handle command-line arguments
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-user"))
username = args[++i];
else if (args[i].equals("-pass"))
password = args[++i];
else if (args[i].equals("-host"))
hostname = args[++i];
else if (args[i].equals("-port"))
port = Integer.parseInt(args[++i]);
else if (args[i].equals("-size"))
sizelimit = Integer.parseInt(args[++i]);
else if (args[i].equals("-subject"))
subjectPattern = args[++i];
else if (args[i].equals("-debug"))
debug = true;
else if (args[i].equals("-delete"))
delete = true;
else if (args[i].equals("-force")) // don"t confirm
confirm = false;
}
// Verify them
if (hostname == null || username == null || password == null || sizelimit == -1)
usage();
// Make sure the pattern is a valid regexp
if (subjectPattern != null) {
pattern = Pattern.rupile(subjectPattern);
matcher = pattern.matcher("");
}
// Say what we are going to do
System.out.println("Connecting to " + hostname + " on port " + port + " with username "
+ username + ".");
if (delete) {
System.out.println("Will delete all messages longer than " + sizelimit + " bytes");
if (subjectPattern != null)
System.out.println("that have a subject matching: [" + subjectPattern + "]");
} else {
System.out.println("Will list subject lines for messages " + "longer than " + sizelimit
+ " bytes");
if (subjectPattern != null)
System.out.println("that have a subject matching: [" + subjectPattern + "]");
}
// If asked to delete, ask for confirmation unless -force is given
if (delete && confirm) {
System.out.println();
System.out.print("Do you want to proceed (y/n) [n]: ");
System.out.flush();
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String response = console.readLine();
if (!response.equals("y")) {
System.out.println("No messages deleted.");
System.exit(0);
}
}
// Connect to the server, and set up streams
s = new Socket(hostname, port);
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
// Read the welcome message from the server, confirming it is OK.
System.out.println("Connected: " + checkResponse());
// Now log in
send("USER " + username); // Send username, wait for response
send("PASS " + password); // Send password, wait for response
System.out.println("Logged in");
// Check how many messages are waiting, and report it
String stat = send("STAT");
StringTokenizer t = new StringTokenizer(stat);
System.out.println(t.nextToken() + " messages in mailbox.");
System.out.println("Total size: " + t.nextToken());
// Get a list of message numbers and sizes
send("LIST"); // Send LIST command, wait for OK response.
// Now read lines from the server until we get . by itself
List msgs = new ArrayList();
String line;
for (;;) {
line = in.readLine();
if (line == null)
throw new IOException("Unexpected EOF");
if (line.equals("."))
break;
msgs.add(line);
}
// Now loop through the lines we read one at a time.
// Each line should specify the message number and its size.
int nummsgs = msgs.size();
for (int i = 0; i < nummsgs; i++) {
String m = (String) msgs.get(i);
StringTokenizer st = new StringTokenizer(m);
int msgnum = Integer.parseInt(st.nextToken());
int msgsize = Integer.parseInt(st.nextToken());
// If the message is too small, ignore it.
if (msgsize <= sizelimit)
continue;
// If we"re listing messages, or matching subject lines
// find the subject line for this message
String subject = null;
if (!delete || pattern != null) {
subject = getSubject(msgnum); // get the subject line
// If we couldn"t find a subject, skip the message
if (subject == null)
continue;
// If this subject does not match the pattern, then
// skip the message
if (pattern != null) {
matcher.reset(subject);
if (!matcher.matches())
continue;
}
// If we are listing, list this message
if (!delete) {
System.out.println("Subject " + msgnum + ": " + subject);
continue; // so we never delete it
}
}
// If we were asked to delete, then delete the message
if (delete) {
send("DELE " + msgnum);
if (pattern == null)
System.out.println("Deleted message " + msgnum);
else
System.out.println("Deleted message " + msgnum + ": " + subject);
}
}
// When we"re done, log out and shutdown the connection
shutdown();
} catch (Exception e) {
// If anything goes wrong print exception and show usage
System.err.println(e);
usage();
// Always try to shutdown nicely so the server doesn"t hang on us
shutdown();
}
}
// Explain how to use the program
public static void usage() {
System.err.println("java PopClean <options>");
System.err.println("Options are:\n" + "-host <hostname> # Required\n"
+ "-port <port> # Optional; default is 110\n" + "-user <username> # Required\n"
+ "-pass <password> # Required and sent as cleartext; APOP not supported\n"
+ "-size <limit> # Message size in bytes. Shorter messages are ignored.\n"
+ "-subject <regexp> # Optional java.util.regex.Pattern regular expression\n"
+ " # only messages with a matching Subject line are deleted\n"
+ "-delete # Delete messages; the default is just to list them\n"
+ "-force # Don"t ask for confirmation before deleting\n"
+ "-debug # Display POP3 protocol requests and responses\n");
System.exit(1);
}
// Send a POP3 command to the server and return its response
public static String send(String cmd) throws IOException {
if (debug)
System.out.println(">>>" + cmd);
out.print(cmd); // Send command
out.print("\r\n"); // and line terminator.
out.flush(); // Send it now!
String response = checkResponse(); // Get the response.
if (debug)
System.out.println("<<<+OK " + response);
return response;
}
// Wait for a response and make sure it is an "OK" response.
public static String checkResponse() throws IOException {
String response;
for (;;) {
response = in.readLine();
if (response == null)
throw new IOException("Server unexpectedly closed connection");
else if (response.startsWith("-ERR"))
throw new IOException("Error from server: " + response);
else if (response.startsWith("+OK"))
return response.substring(3);
}
}
// Ask the server to send the headers of the numbered message.
// Look through them for the Subject header and return its content.
public static String getSubject(int msgnum) throws IOException {
send("TOP " + msgnum + " 0");
String subject = null, line;
for (;;) {
line = in.readLine();
if (line == null)
throw new IOException("Unexpected EOF");
if (line.startsWith("Subject: "))
subject = line.substring(9);
if (line.equals("."))
break;
}
return subject;
}
// Disconnect nicely from the POP server.
// This method is called for normal termination and exceptions.
public static void shutdown() {
try {
if (out != null) {
send("QUIT");
out.close();
}
if (in != null)
in.close();
if (s != null)
s.close();
} catch (IOException e) {
}
}
}
Demonstrate Sockets.
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
class Whois {
public static void main(String args[]) throws Exception {
int c;
Socket s = new Socket("internic.net", 43);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
String str = "asdfasdfasdf\n";
byte buf[] = str.getBytes();
out.write(buf);
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
s.close();
}
}
Download WWW Page
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
class Main{
public String downloadWWWPage(URL pageURL) throws Exception {
String host, file;
host = pageURL.getHost();
file = pageURL.getFile();
InputStream pageStream = getWWWPageStream(host, file);
if (pageStream == null) {
return "";
}
DataInputStream in = new DataInputStream(pageStream);
StringBuffer pageBuffer = new StringBuffer();
String line;
while ((line = in.readUTF()) != null) {
pageBuffer.append(line);
}
in.close();
return pageBuffer.toString();
}
public InputStream getWWWPageStream(String host, String file) throws IOException,
UnknownHostException {
InetAddress webServer = InetAddress.getByName(host);
Socket httpPipe = new Socket(webServer, 80);
if (httpPipe == null) {
System.out.println("Socket to Web server creation failed.");
return null;
}
InputStream inn = httpPipe.getInputStream(); // get raw streams
OutputStream outt = httpPipe.getOutputStream();
DataInputStream in = new DataInputStream(inn); // turn into higher-level ones
PrintStream out = new PrintStream(outt);
if (inn == null || outt == null) {
System.out.println("Failed to open streams to socket.");
return null;
}
out.println("GET " + file + " HTTP/1.0\n");
String response;
while ((response = in.readUTF()).length() > 0) {
System.out.println(response);
}
return in;
}
}
Get email with Socket
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class POP3Demo {
public static void main(String[] args) throws Exception {
int POP3Port = 110;
Socket client = new Socket("127.0.0.1", POP3Port);
InputStream is = client.getInputStream();
BufferedReader sockin = new BufferedReader(new InputStreamReader(is));
OutputStream os = client.getOutputStream();
PrintWriter sockout = new PrintWriter(os, true);
String cmd = "user Smith";
sockout.println(cmd);
String reply = sockin.readLine();
cmd = "pass ";
sockout.println(cmd + "popPassword");
reply = sockin.readLine();
cmd = "stat";
sockout.println(cmd);
reply = sockin.readLine();
if (reply == null)
return;
cmd = "retr 1";
sockout.println(cmd);
if (cmd.toLowerCase().startsWith("retr") && reply.charAt(0) == "+")
do {
reply = sockin.readLine();
System.out.println("S:" + reply);
if (reply != null && reply.length() > 0)
if (reply.charAt(0) == ".")
break;
} while (true);
cmd = "quit";
sockout.println(cmd);
client.close();
}
}
Get the Date from server
import java.io.InputStream;
import java.net.Socket;
public class Main {
public static void main(String args[]) throws Exception{
Socket s = new Socket(args[0], 13);
InputStream is = s.getInputStream();
while (true) {
byte b[] = new byte[100];
int i = is.read(b);
if (i == -1)
break;
System.out.print(new String(b, 0, i));
}
}
}
ObjectInputStream and ObjectOutputStream from Socket
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class LoopingSocketClient {
public static void main(String args[]) throws Exception {
Socket socket1;
int portNumber = 1777;
String str = "";
socket1 = new Socket(InetAddress.getLocalHost(), portNumber);
ObjectInputStream ois = new ObjectInputStream(socket1.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket1.getOutputStream());
str = "initialize";
oos.writeObject(str);
while ((str = (String) ois.readObject()) != null) {
System.out.println(str);
oos.writeObject("bye");
if (str.equals("bye bye"))
break;
}
ois.close();
oos.close();
socket1.close();
}
}
Ping a server
import java.io.DataInputStream;
import java.io.PrintStream;
import java.net.Socket;
public class Main {
public static void main(String[] argv) throws Exception {
Socket t = new Socket("127.0.0.1", 7);
DataInputStream dis = new DataInputStream(t.getInputStream());
PrintStream ps = new PrintStream(t.getOutputStream());
ps.println("Hello");
String str = dis.readUTF();
if (str.equals("Hello"))
System.out.println("Alive!");
else
System.out.println("Dead");
t.close();
}
}
Read and write through socket
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Main {
public static void whois(String query, String server) throws IOException {
Socket sock = new Socket(server, 43);
int c = 0;
OutputStream os = sock.getOutputStream();
InputStream is = sock.getInputStream();
query += "\r\n";
os.write(query.getBytes("iso8859_1"));
while (c != -1) {
c = is.read();
if (c != -1)
System.out.println((char) c);
}
}
public static void main(String[] args) throws Exception {
String hostname = "whois.networksolutions.ru";
whois("query", hostname);
}
}
Read float number from a Socket
import java.io.DataInputStream;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws Exception {
Socket sock = new Socket(args[0], 1234);
DataInputStream dis = new DataInputStream(sock.getInputStream());
float f = dis.readFloat();
System.out.println("PI=" + f);
dis.close();
sock.close();
}
}
Read from server
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.Socket;
class SocketDemo {
public static void main(String args[]) throws Exception {
String server = args[0];
int port = Integer.parseInt(args[1]);
Socket s = new Socket(server, port);
InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
System.out.println(dis.readInt());
s.close();
}
}
Reading Text from a Socket
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] argv) throws Exception {
int port = 2000;
ServerSocket srv = new ServerSocket(port);
// Wait for connection from client.
Socket socket = srv.accept();
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str;
while ((str = rd.readLine()) != null) {
System.out.println(str);
}
rd.close();
}
}
Read Object from Socket
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.Hashtable;
public class Main{
public static void main(String[] args) throws Exception {
Socket sock = new Socket(args[0], 1234);
ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
Hashtable hash = (Hashtable) ois.readObject();
System.out.println(hash);
ois.close();
sock.close();
}
}
Redirects incoming TCP connections to other hosts/ports
// $Id: Proxy.java,v 1.3.4.1 2008/01/22 10:01:16 belaban Exp $
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Redirects incoming TCP connections to other hosts/ports. All redirections are defined in a file as for example
* <pre>
* 127.0.0.1:8888=www.ibm.ru:80
* localhost:80=pop.mail.yahoo.ru:110
* </pre>
* The first line forwards all requests to port 8888 on to www.ibm.ru at port 80 (it also forwards the HTTP
* response back to the sender. The second line essentially provides a POP-3 service on port 8110, using
* Yahoo"s POP service. This is neat when you"re behind a firewall and one of the few services in the outside
* world that are not blocked is port 80 (HHTP).<br/>
* Note that JDK 1.4 is required for this class. Also, concurrent.jar has to be on the classpath. Note that
* you also need to include jsse.jar/jce.jar (same location as rt.jar) if you want SSL sockets.<br>
* To create SSLServerSockets you"ll need to do the following:
* Generate a certificate as follows:
* <pre>
* keytool -genkey -keystore /home/bela/.keystore -keyalg rsa -alias bela -storepass <passwd> -keypass <passwd>
* </pre>
*
* Start the Proxy as follows:
* <pre>
* java -Djavax.net.ssl.keyStore=/home/bela/.keystore -Djavax.net.ssl.keyStorePassword=<passwd>
* -Djavax.net.ssl.trustStore=/home/bela/.keystore -Djavax.net.ssl.trustStorePassword=<passwd>
* org.jgroups.util.Proxy -file /home/bela/map.properties
* </pre>
* Start client as follows:
* <pre>
* java -Djavax.net.ssl.trustStore=/home/bela/.keystore -Djavax.net.ssl.trustStorePassword=<passwd> sslclient
* </pre>
* <br/>
* To import a certificate into the keystore, use the following steps:
* <pre>
* openssl x509 -in server.crt -out server.crt.der -outform DER
* keytool -import -trustcacerts -alias <your alias name> -file server.crt.der
* </pre>
* This will store the server"s certificate in the ${user.home}/.keystore key store.
* <br/>
* Note that an SSL client or server can be debugged by starting it as follows:
* <pre>-Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol -Djavax.net.debug=ssl</pre>
* <br/>
* If you run a web browser, simply enter https://<host>:<port> as URL to connect to an SSLServerSocket
* <br/>Note that we cannot use JDK 1.4"s selectors for SSL sockets, as
* getChannel() on an SSL socket doesn"t seem to work.
* @todo Check whether SSLSocket.getChannel() or SSLServerSocket.getChannel() works.
* @author Bela Ban
*/
public class Proxy {
InetAddress local=null, remote=null;
int local_port=0, remote_port=0;
static boolean verbose=false;
static boolean debug=false;
String mapping_file=null; // contains a list of src and dest host:port pairs
final HashMap mappings=new HashMap(); // keys=MyInetSocketAddr (src), values=MyInetSocketAddr (dest)
Executor executor; // maintains a thread pool
static final int MIN_THREAD_POOL_SIZE=2;
static final int MAX_THREAD_POOL_SIZE=64; // for processing requests
static final int BUFSIZE=1024; // size of data transfer buffer
public Proxy(InetAddress local, int local_port, InetAddress remote, int remote_port, boolean verbose, boolean debug) {
this.local=local;
this.local_port=local_port;
this.remote=remote;
this.remote_port=remote_port;
Proxy.verbose=verbose;
Proxy.debug=debug;
}
public Proxy(InetAddress local, int local_port, InetAddress remote, int remote_port,
boolean verbose, boolean debug, String mapping_file) {
this(local, local_port, remote, remote_port, verbose, debug);
this.mapping_file=mapping_file;
}
public void start() throws Exception {
Map.Entry entry;
Selector selector;
ServerSocketChannel sock_channel;
MyInetSocketAddress key, value;
if (remote !=null && local !=null)
mappings.put(new InetSocketAddress(local, local_port), new InetSocketAddress(remote, remote_port));
if (mapping_file !=null) {
try {
populateMappings(mapping_file);
}
catch (Exception ex) {
log("Failed reading " + mapping_file);
throw ex;
}
}
log("\nProxy started at " + new java.util.Date());
if (verbose) {
log("\nMappings:\n---------");
for (Iterator it=mappings.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry) it.next();
log(toString((InetSocketAddress) entry.getKey()) + " <--> "
+ toString((InetSocketAddress) entry.getValue()));
}
log("\n");
}
// 1. Create a Selector
selector=Selector.open();
// Create a thread pool (Executor)
executor=new ThreadPoolExecutor(MIN_THREAD_POOL_SIZE, MAX_THREAD_POOL_SIZE, 30000, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue(1000));
for (Iterator it=mappings.keySet().iterator(); it.hasNext();) {
key=(MyInetSocketAddress) it.next();
value=(MyInetSocketAddress) mappings.get(key);
// if either source or destination are SSL, we cannot use JDK 1.4
// NIO selectors, but have to fall back on separate threads per connection
if (key.ssl() || value.ssl()) {
// if(2 == 2) {
SocketAcceptor acceptor=new SocketAcceptor(key, value);
executor.execute(acceptor);
continue;
}
// 2. Create a ServerSocketChannel
sock_channel=ServerSocketChannel.open();
sock_channel.configureBlocking(false);
sock_channel.socket().bind(key);
// 3. Register the selector with all server sockets. "Key" is attachment, so we get it again on
// select(). That way we can associate it with the mappings hashmap to find the corresponding
// value
sock_channel.register(selector, SelectionKey.OP_ACCEPT, key);
}
// 4. Start main loop. won"t return until CTRL-C"ed
loop(selector);
}
/** We handle only non-SSL connections */
void loop(Selector selector) {
Set ready_keys;
SelectionKey key;
ServerSocketChannel srv_sock;
SocketChannel in_sock, out_sock;
InetSocketAddress src, dest;
while (true) {
if (verbose)
log("[Proxy] ready to accept connection");
// 4. Call Selector.select()
try {
selector.select();
// get set of ready objects
ready_keys=selector.selectedKeys();
for (Iterator it=ready_keys.iterator(); it.hasNext();) {
key=(SelectionKey) it.next();
it.remove();
if (key.isAcceptable()) {
srv_sock=(ServerSocketChannel) key.channel();
// get server socket and attachment
src=(InetSocketAddress) key.attachment();
in_sock=srv_sock.accept(); // accept request
if (verbose)
log("Proxy.loop()", "accepted connection from " + toString(in_sock));
dest=(InetSocketAddress) mappings.get(src);
// find corresponding dest
if (dest == null) {
in_sock.close();
log("Proxy.loop()", "did not find a destination host for " + src);
continue;
}
else {
if (verbose)
log("Proxy.loop()", "relaying traffic from " + toString(src) + " to " + toString(dest));
}
// establish connection to destination host
try {
out_sock=SocketChannel.open(dest);
// uses thread pool (Executor) to handle request, closes socks at end
handleConnection(in_sock, out_sock);
}
catch (Exception ex) {
in_sock.close();
throw ex;
}
}
}
}
catch (Exception ex) {
log("Proxy.loop()", "exception: " + ex);
}
}
}
// void handleConnection(Socket in_sock, Socket out_sock) {
// try {
// Relayer r=new Relayer(in_sock, out_sock);
// executor.execute(r);
// r=new Relayer(out_sock, in_sock);
// executor.execute(r);
// }
// catch (Exception ex) {
// log("Proxy.handleConnection()", "exception: " + ex);
// }
// finally {
// close(in_sock, out_sock);
// }
// }
void handleConnection(SocketChannel in, SocketChannel out) {
try {
_handleConnection(in, out);
}
catch (Exception ex) {
log("Proxy.handleConnection()", "exception: " + ex);
}
}
void _handleConnection(final SocketChannel in_channel, final SocketChannel out_channel) throws Exception {
executor.execute(new Runnable() {
public void run() {
Selector sel=null;
SocketChannel tmp;
Set ready_keys;
SelectionKey key;
ByteBuffer transfer_buf=ByteBuffer.allocate(BUFSIZE);
try {
sel=Selector.open();
in_channel.configureBlocking(false);
out_channel.configureBlocking(false);
in_channel.register(sel, SelectionKey.OP_READ);
out_channel.register(sel, SelectionKey.OP_READ);
while (sel.select() > 0) {
ready_keys=sel.selectedKeys();
for (Iterator it=ready_keys.iterator(); it.hasNext();) {
key=(SelectionKey) it.next();
it.remove(); // remove current entry (why ?)
tmp=(SocketChannel) key.channel();
if (tmp == null) {
log(
"Proxy._handleConnection()",
"attachment is null, continuing");
continue;
}
if (key.isReadable()) { // data is available to be read from tmp
if (tmp == in_channel) {
// read all data from in_channel and forward it to out_channel (request)
if (relay(tmp, out_channel, transfer_buf) == false)
return;
}
if (tmp == out_channel) {
// read all data from out_channel and forward it
// to in_channel (response)
if (relay(tmp, in_channel, transfer_buf) == false)
return;
}
}
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
close(sel, in_channel, out_channel);
}
}
});
}
void close(Selector sel, SocketChannel in_channel, SocketChannel out_channel) {
try {
if (sel !=null)
sel.close();
}
catch (Exception ex) {
}
try {
if (in_channel !=null)
in_channel.close();
}
catch (Exception ex) {
}
try {
if (out_channel !=null)
out_channel.close();
}
catch (Exception ex) {
}
}
/**
* Read all data from <code>from</code> and write it to <code>to</code>.
* Returns false if channel was closed
*/
boolean relay(SocketChannel from, SocketChannel to, ByteBuffer buf) throws Exception {
int num;
StringBuilder sb;
buf.clear();
while (true) {
num=from.read(buf);
if (num < 0)
return false;
else
if (num == 0)
return true;
buf.flip();
if (verbose) {
log(printRelayedData(toString(from), toString(to), buf.remaining()));
}
if (debug) {
sb=new StringBuilder();
sb.append(new String(buf.array()).trim());
sb.append("\n");
log(sb.toString());
}
to.write(buf);
buf.flip();
}
}
String toString(SocketChannel ch) {
StringBuilder sb=new StringBuilder();
Socket sock;
if (ch == null)
return null;
if ((sock=ch.socket()) == null)
return null;
sb.append(sock.getInetAddress().getHostName()).append(":").append(sock.getPort());
return sb.toString();
}
String toString(InetSocketAddress addr) {
StringBuilder sb;
sb=new StringBuilder();
if (addr == null)
return null;
sb.append(addr.getAddress().getHostName()).append(":").append(addr.getPort());
if (addr instanceof MyInetSocketAddress)
sb.append(" [ssl=").append(((MyInetSocketAddress) addr).ssl()).append("]");
return sb.toString();
}
static String printRelayedData(String from, String to, int num_bytes) {
StringBuilder sb;
sb=new StringBuilder();
sb.append("\n[PROXY] ").append(from);
sb.append(" to ").append(to);
sb.append(" (").append(num_bytes).append(" bytes)");
// log("Proxy.relay()", sb.toString());
return sb.toString();
}
/**
* Populates <code>mappings</code> hashmap. An example of a definition file is:
* <pre>
* http://localhost:8888=http://www.yahoo.ru:80
* https://localhost:2200=https://cvs.sourceforge.net:22
* http://localhost:8000=https://www.ibm.ru:443
* </pre>
* Mappings can be http-https, https-http, http-http or https-https
*/
void populateMappings(String filename) throws Exception {
FileInputStream in=new FileInputStream(filename);
BufferedReader reader;
String line;
URI key, value;
int index;
boolean ssl_key, ssl_value;
final String HTTPS="https";
reader=new BufferedReader(new InputStreamReader(in));
while ((line=reader.readLine()) !=null) {
line=line.trim();
if (line.startsWith("//") || line.startsWith("#") || line.length() == 0)
continue;
index=line.indexOf("=");
if (index == -1)
throw new Exception("Proxy.populateMappings(): detected no "=" character in " + line);
key=new URI(line.substring(0, index));
ssl_key=key.getScheme().trim().equals(HTTPS);
value=new URI(line.substring(index + 1));
ssl_value=value.getScheme().trim().equals(HTTPS);
check(key);
check(value);
log("key: " + key + ", value: " + value);
mappings.put(new MyInetSocketAddress(key.getHost(), key.getPort(), ssl_key),
new MyInetSocketAddress(value.getHost(), value.getPort(), ssl_value));
}
in.close();
}
/** Checks whether a URI is http(s)://<host>:<port> */
void check(URI u) throws Exception {
if (u.getScheme() == null)
throw new Exception(
"scheme is null in " + u + ", (valid URI is \"http(s)://<host>:<port>\")");
if (u.getHost() == null)
throw new Exception(
"host is null in " + u + ", (valid URI is \"http(s)://<host>:<port>\")");
if (u.getPort() <=0)
throw new Exception(
"port is <=0 in " + u + ", (valid URI is \"http(s)://<host>:<port>\")");
}
/** Input is "host:port" */
SocketAddress strToAddr(String input) throws Exception {
StringTokenizer tok=new StringTokenizer(input, ":");
String host, port;
host=tok.nextToken();
port=tok.nextToken();
return new InetSocketAddress(host, Integer.parseInt(port));
}
String printSelectionOps(SelectionKey key) {
StringBuilder sb=new StringBuilder();
if ((key.readyOps() & SelectionKey.OP_ACCEPT) !=0)
sb.append("OP_ACCEPT ");
if ((key.readyOps() & SelectionKey.OP_CONNECT) !=0)
sb.append("OP_CONNECT ");
if ((key.readyOps() & SelectionKey.OP_READ) !=0)
sb.append("OP_READ ");
if ((key.readyOps() & SelectionKey.OP_WRITE) !=0)
sb.append("OP_WRITE ");
return sb.toString();
}
public static void main(String[] args) {
Proxy p;
InetAddress local=null, remote=null;
int local_port=0, remote_port=0;
String tmp, tmp_addr, tmp_port;
boolean verbose=false, debug=false;
int index;
String mapping_file=null;
try {
for (int i=0; i < args.length; i++) {
tmp=args[i];
if ("-help".equals(tmp)) {
help();
return;
}
if ("-verbose".equals(tmp)) {
verbose=true;
continue;
}
if ("-local".equals(tmp)) {
tmp_addr=args[++i];
index=tmp_addr.indexOf(":");
if (index > -1) { // it is in the format address:port
tmp_port=tmp_addr.substring(index + 1);
local_port=Integer.parseInt(tmp_port);
tmp_addr=tmp_addr.substring(0, index);
local=InetAddress.getByName(tmp_addr);
}
else
local=InetAddress.getByName(args[++i]);
continue;
}
if ("-local_port".equals(tmp)) {
local_port=Integer.parseInt(args[++i]);
continue;
}
if ("-remote".equals(tmp)) {
tmp_addr=args[++i];
index=tmp_addr.indexOf(":");
if (index > -1) { // it is in the format address:port
tmp_port=tmp_addr.substring(index + 1);
remote_port=Integer.parseInt(tmp_port);
tmp_addr=tmp_addr.substring(0, index);
remote=InetAddress.getByName(tmp_addr);
}
else
remote=InetAddress.getByName(args[++i]);
continue;
}
if ("-remote_port".equals(tmp)) {
remote_port=Integer.parseInt(args[++i]);
continue;
}
if ("-file".equals(tmp)) {
mapping_file=args[++i];
continue;
}
if ("-debug".equals(tmp)) {
debug=true;
continue;
}
help();
return;
}
if (local == null)
local=InetAddress.getLocalHost();
p=new Proxy(local, local_port, remote, remote_port, verbose, debug, mapping_file);
p.start();
}
catch (Throwable ex) {
ex.printStackTrace();
}
}
static void help() {
System.out.println("Proxy [-help] [-local <local address>] [-local_port <port>] "
+ "[-remote <remote address>] [-remote_port <port>] [-verbose] "
+ "[-file <mapping file>] [-debug]");
}
static void log(String method_name, String msg) {
System.out.println("[" + method_name + "]: " + msg);
}
static void log(String msg) {
System.out.println(msg);
}
static void close(Socket in, Socket out) {
if (in !=null) {
try {
in.close();
}
catch (Exception ex) {
}
}
if (out !=null) {
try {
out.close();
}
catch (Exception ex) {
}
}
}
static void close(Socket sock) {
if (sock !=null) {
try {
sock.close();
}
catch (Exception ex) {
}
}
}
static class Relayer implements Runnable {
final Socket in_sock;
final Socket out_sock;
final InputStream in;
final OutputStream out;
Thread t=null;
final java.util.List listeners=new ArrayList();
String name=null;
interface Listener {
void connectionClosed();
}
public Relayer(Socket in_sock, Socket out_sock, String name) throws Exception {
this.in_sock=in_sock;
this.out_sock=out_sock;
this.name=name;
in=in_sock.getInputStream();
out=out_sock.getOutputStream();
}
public void addListener(Listener l) {
if(l != null && !listeners.contains(l))
listeners.add(l);
}
public void run() {
byte[] buf=new byte[1024];
int num;
StringBuilder sb;
try {
while(t != null) {
if ((num=in.read(buf)) == -1)
break;
if (verbose) {
//sb=new StringBuilder();
//sb.append("forwarding ").append(num).append(" bytes from ").append(toString(in_sock));
//sb.append(" to ").append(toString(out_sock));
// log("Proxy.Relayer.run()", sb.toString());
log(printRelayedData(toString(in_sock), toString(out_sock), num));
}
if (debug) {
sb=new StringBuilder();
sb.append(new String(buf, 0, num).trim());
log(sb.toString());
}
out.write(buf, 0, num);
//if(debug)
// System.out.println(new String(buf));
}
}
catch (Exception ex) {
log("Proxy.Relayer.run(): [" + name + "] exception=" + ex + ", in_sock=" +
in_sock + ", out_sock=" + out_sock);
}
finally {
stop();
}
}
public void start() {
if(t == null) {
t=new Thread(this, "Proxy.Relayer");
t.setDaemon(true);
t.start();
}
}
public void stop() {
t=null;
close(in_sock);
close(out_sock);
}
String toString(Socket s) {
if(s == null) return null;
return s.getInetAddress().getHostName() + ":" + s.getPort();
}
void notifyListeners() {
for(Iterator it=listeners.iterator(); it.hasNext();) {
try {
((Listener)it.next()).connectionClosed();
}
catch(Throwable ex) {
;
}
}
}
}
static class MyInetSocketAddress extends InetSocketAddress {
boolean is_ssl=false;
public MyInetSocketAddress(InetAddress addr, int port) {
super(addr, port);
}
public MyInetSocketAddress(InetAddress addr, int port, boolean is_ssl) {
super(addr, port);
this.is_ssl=is_ssl;
}
public MyInetSocketAddress(int port) {
super(port);
}
public MyInetSocketAddress(int port, boolean is_ssl) {
super(port);
this.is_ssl=is_ssl;
}
public MyInetSocketAddress(String hostname, int port) {
super(hostname, port);
}
public MyInetSocketAddress(String hostname, int port, boolean is_ssl) {
super(hostname, port);
this.is_ssl=is_ssl;
}
public boolean ssl() {
return is_ssl;
}
public String toString() {
return super.toString() + " [ssl: " + ssl() + "]";
}
}
/**
* Handles accepts on an SSLServerSocket or ServerSocket. Creates a {@link
* Connection} for each successful accept().
*
* @author bela Dec 19, 2002
*/
class SocketAcceptor implements Runnable {
ServerSocket srv_sock=null;
MyInetSocketAddress dest=null;
/**
* Create an SSLServerSocket or ServerSocket and continuously call
* accept() on it.
* @param sock_addr
*/
public SocketAcceptor(MyInetSocketAddress sock_addr, MyInetSocketAddress dest) throws Exception {
this.dest=dest;
if(sock_addr.ssl()) {
srv_sock=createSSLServerSocket(sock_addr);
}
else {
srv_sock=createServerSocket(sock_addr);
}
executor.execute(this);
}
public void run() {
Connection conn;
Socket s, dest_sock;
while (srv_sock !=null) {
try {
s=srv_sock.accept();
dest_sock=dest.ssl() ? createSSLSocket(dest) : createSocket(dest);
conn=new Connection(s, dest_sock);
conn.start();
}
catch (Exception e) {
log("Proxy.SSLServerSocketAcceptor.run(): exception=" + e);
break;
}
}
}
Socket createSocket(InetSocketAddress addr) throws Exception {
return new Socket(addr.getAddress(), addr.getPort());
}
Socket createSSLSocket(InetSocketAddress addr) throws Exception {
SSLSocketFactory sslsocketfactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
return sslsocketfactory.createSocket(addr.getAddress(), addr.getPort());
}
ServerSocket createServerSocket(InetSocketAddress addr) throws Exception {
return new ServerSocket(addr.getPort(), 10, addr.getAddress());
}
ServerSocket createSSLServerSocket(InetSocketAddress addr) throws Exception {
SSLServerSocketFactory sslserversocketfactory =
(SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
SSLServerSocket sslserversocket;
sslserversocket=(SSLServerSocket)sslserversocketfactory.createServerSocket(addr.getPort(), 10, addr.getAddress());
return sslserversocket;
}
}
/**
* Handles an incoming SSLSocket or Socket. Looks up the destination in the
* mapping hashmap, key is the incoming socket address. Creates an outgoing
* socket (regular or SSL, depending on settings) and relays data between
* incoming and outgoing sockets. Closes the connection when either incoming
* or outgoing socket is closed, or when stop() is called.
*
* @author bela Dec 19, 2002
*/
static class Connection implements Relayer.Listener {
Relayer in_to_out=null;
Relayer out_to_in=null;
/**
* Creates an outgoing (regular or SSL) socket according to the mapping
* table. Sets both input and output stream. Caller needs to call
* start() after the instance has been created.
* @param in The Socket we got as result of accept()
* @throws Exception Thrown if either the input or output streams cannot
* be created.
*/
public Connection(Socket in, Socket out) throws Exception {
in_to_out=new Relayer(in, out, "in-out");
in_to_out.addListener(this);
out_to_in=new Relayer(out, in, "out-in");
out_to_in.addListener(this);
}
/** Starts relaying between incoming and outgoing sockets.
* Returns immediately (thread is started).
*
*/
public void start() {
in_to_out.start();
out_to_in.start();
}
public void stop() {
if (in_to_out !=null) {
in_to_out.stop();
}
if (out_to_in !=null) {
out_to_in.stop();
}
}
public void connectionClosed() {
stop();
}
}
}
Sending a POST Request Using a Socket
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URLEncoder;
public class Main {
public static void main(String[] argv) throws Exception {
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
Socket socket = new Socket("127.0.0.1", 8080);
String path = "/servlet";
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
wr.write("POST " + path + " HTTP/1.0\r\n");
wr.write("Content-Length: " + data.length() + "\r\n");
wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
wr.write("\r\n");
wr.write(data);
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
}
}
ServerSocket and Socket for Serializable object
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Iterator;
import java.util.Vector;
class ComplexCompany implements Serializable {
private String name;
private ComplexEmployee president;
private Vector departments;
public ComplexCompany(String name) {
this.name = name;
departments = new Vector();
}
public String getName() {
return this.name;
}
public void addDepartment(ComplexDepartment dept) {
departments.addElement(dept);
}
public ComplexEmployee getPresident() {
return this.president;
}
public void addPresident(ComplexEmployee e) {
this.president = e;
}
public Iterator getDepartmentIterator() {
return departments.iterator();
}
public void printCompanyObject() {
System.out.println("The company name is " + getName());
System.out.println("The company president is " + getPresident().getName());
System.out.println(" ");
Iterator i = getDepartmentIterator();
while (i.hasNext()) {
ComplexDepartment d = (ComplexDepartment) i.next();
System.out.println(" The department name is " + d.getName());
System.out.println(" The department manager is " + d.getManager().getName());
System.out.println(" ");
}
}
}
class ComplexDepartment implements Serializable {
private String name;
private ComplexEmployee manager;
public ComplexDepartment(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public ComplexEmployee getManager() {
return this.manager;
}
public void addManager(ComplexEmployee e) {
manager = e;
}
}
class ComplexEmployee implements Serializable {
private String name;
private int salary;
/** Creates a new instance of ComplexEmployee */
public ComplexEmployee(String name, int salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public int getSalary() {
return this.salary;
}
}
public class ComplexSocketServer {
public static void main(String args[]) throws Exception {
ServerSocket servSocket;
Socket fromClientSocket;
int cTosPortNumber = 1777;
String str;
ComplexCompany comp;
servSocket = new ServerSocket(cTosPortNumber);
System.out.println("Waiting for a connection on " + cTosPortNumber);
fromClientSocket = servSocket.accept();
ObjectOutputStream oos = new ObjectOutputStream(fromClientSocket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(fromClientSocket.getInputStream());
while ((comp = (ComplexCompany) ois.readObject()) != null) {
comp.printCompanyObject();
oos.writeObject("bye bye");
break;
}
oos.close();
fromClientSocket.close();
}
}
public class ComplexSocketClient {
public static void main(String args[]) throws Exception {
Socket socket1;
int portNumber = 1777;
String str = "";
socket1 = new Socket(InetAddress.getLocalHost(), portNumber);
ObjectInputStream ois = new ObjectInputStream(socket1.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket1.getOutputStream());
ComplexCompany comp = new ComplexCompany("A");
ComplexEmployee emp0 = new ComplexEmployee("B", 1000);
comp.addPresident(emp0);
ComplexDepartment sales = new ComplexDepartment("C");
ComplexEmployee emp1 = new ComplexEmployee("D", 1200);
sales.addManager(emp1);
comp.addDepartment(sales);
ComplexDepartment accounting = new ComplexDepartment("E");
ComplexEmployee emp2 = new ComplexEmployee("F", 1230);
accounting.addManager(emp2);
comp.addDepartment(accounting);
ComplexDepartment maintenance = new ComplexDepartment("Maintenance");
ComplexEmployee emp3 = new ComplexEmployee("Greg Hladlick", 1020);
maintenance.addManager(emp3);
comp.addDepartment(maintenance);
oos.writeObject(comp);
while ((str = (String) ois.readObject()) != null) {
System.out.println(str);
oos.writeObject("bye");
if (str.equals("bye"))
break;
}
ois.close();
oos.close();
socket1.close();
}
}
Socket Address Encoder
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.StringTokenizer;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Encodes and decodes socket addresses (IP and port) from and to the format
* used with for example the PORT and PASV command
*
* @author The Apache MINA Project (dev@mina.apache.org)
*/
public class SocketAddressEncoder {
private static int convertAndValidateNumber(String s) {
int i = Integer.parseInt(s);
if (i < 0) {
throw new IllegalArgumentException("Token can not be less than 0");
} else if (i > 255) {
throw new IllegalArgumentException(
"Token can not be larger than 255");
}
return i;
}
public static InetSocketAddress decode(String str)
throws UnknownHostException {
StringTokenizer st = new StringTokenizer(str, ",");
if (st.countTokens() != 6) {
throw new Exception("Illegal amount of tokens");
}
StringBuffer sb = new StringBuffer();
try {
sb.append(convertAndValidateNumber(st.nextToken()));
sb.append(".");
sb.append(convertAndValidateNumber(st.nextToken()));
sb.append(".");
sb.append(convertAndValidateNumber(st.nextToken()));
sb.append(".");
sb.append(convertAndValidateNumber(st.nextToken()));
} catch (IllegalArgumentException e) {
throw new Exception(e.getMessage());
}
InetAddress dataAddr = InetAddress.getByName(sb.toString());
// get data server port
int dataPort = 0;
try {
int hi = convertAndValidateNumber(st.nextToken());
int lo = convertAndValidateNumber(st.nextToken());
dataPort = (hi << 8) | lo;
} catch (IllegalArgumentException ex) {
throw new Exception("Invalid data port: " + str);
}
return new InetSocketAddress(dataAddr, dataPort);
}
public static String encode(InetSocketAddress address) {
InetAddress servAddr = address.getAddress();
int servPort = address.getPort();
return servAddr.getHostAddress().replace(".", ",") + ","
+ (servPort >> 8) + "," + (servPort & 0xFF);
}
}
Socket connection and concurrent package
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ExecutorHttpd {
ExecutorService executor = Executors.newFixedThreadPool(3);
public void start(int port) throws IOException {
final ServerSocket ss = new ServerSocket(port);
while (!executor.isShutdown())
executor.submit(new TinyHttpdConnection(ss.accept()));
}
public void shutdown() throws InterruptedException {
executor.shutdown();
executor.awaitTermination(30, TimeUnit.SECONDS);
executor.shutdownNow();
}
public static void main(String argv[]) throws Exception {
new ExecutorHttpd().start(Integer.parseInt(argv[0]));
}
}
class TinyHttpdConnection implements Runnable {
Socket client;
TinyHttpdConnection(Socket client) throws SocketException {
this.client = client;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(),
"8859_1"));
OutputStream out = client.getOutputStream();
PrintWriter pout = new PrintWriter(new OutputStreamWriter(out, "8859_1"), true);
String request = in.readLine();
System.out.println("Request: " + request);
byte[] data = "hello".getBytes();
out.write(data, 0, data.length);
out.flush();
client.close();
} catch (IOException e) {
System.out.println("I/O error " + e);
}
}
}
Socket Fetcher
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don"t indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
/*
* @(#)SocketFetcher.java 1.20 07/05/04
*/
import java.security.*;
import java.net.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import javax.net.*;
import javax.net.ssl.*;
/**
* This class is used to get Sockets. Depending on the arguments passed
* it will either return a plain java.net.Socket or dynamically load
* the SocketFactory class specified in the classname param and return
* a socket created by that SocketFactory.
*
* @author Max Spivak
* @author Bill Shannon
*/
public class SocketFetcher {
// No one should instantiate this class.
private SocketFetcher() {
}
/**
* This method returns a Socket. Properties control the use of
* socket factories and other socket characteristics. The properties
* used are: <p>
* <ul>
* <li> <i>prefix</i>.socketFactory.class
* <li> <i>prefix</i>.socketFactory.fallback
* <li> <i>prefix</i>.socketFactory.port
* <li> <i>prefix</i>.timeout
* <li> <i>prefix</i>.connectiontimeout
* <li> <i>prefix</i>.localaddress
* <li> <i>prefix</i>.localport
* </ul> <p>
* If the socketFactory.class property isn"t set, the socket
* returned is an instance of java.net.Socket connected to the
* given host and port. If the socketFactory.class property is set,
* it is expected to contain a fully qualified classname of a
* javax.net.SocketFactory subclass. In this case, the class is
* dynamically instantiated and a socket created by that
* SocketFactory is returned. <p>
*
* If the socketFactory.fallback property is set to false, don"t
* fall back to using regular sockets if the socket factory fails. <p>
*
* The socketFactory.port specifies a port to use when connecting
* through the socket factory. If unset, the port argument will be
* used. <p>
*
* If the connectiontimeout property is set, we use a separate thread
* to make the connection so that we can timeout that connection attempt.
* <p>
*
* If the timeout property is set, it is used to set the socket timeout.
* <p>
*
* If the localaddress property is set, it"s used as the local address
* to bind to. If the localport property is also set, it"s used as the
* local port number to bind to.
*
* @param host The host to connect to
* @param port The port to connect to at the host
* @param props Properties object containing socket properties
* @param prefix Property name prefix, e.g., "mail.imap"
* @param useSSL use the SSL socket factory as the default
*/
public static Socket getSocket(String host, int port, Properties props,
String prefix, boolean useSSL)
throws IOException {
if (prefix == null)
prefix = "socket";
if (props == null)
props = new Properties(); // empty
String s = props.getProperty(prefix + ".connectiontimeout", null);
int cto = -1;
if (s != null) {
try {
cto = Integer.parseInt(s);
} catch (NumberFormatException nfex) { }
}
Socket socket = null;
String timeout = props.getProperty(prefix + ".timeout", null);
String localaddrstr = props.getProperty(prefix + ".localaddress", null);
InetAddress localaddr = null;
if (localaddrstr != null)
localaddr = InetAddress.getByName(localaddrstr);
String localportstr = props.getProperty(prefix + ".localport", null);
int localport = 0;
if (localportstr != null) {
try {
localport = Integer.parseInt(localportstr);
} catch (NumberFormatException nfex) { }
}
boolean fb = false;
String fallback =
props.getProperty(prefix + ".socketFactory.fallback", null);
fb = fallback == null || (!fallback.equalsIgnoreCase("false"));
String sfClass =
props.getProperty(prefix + ".socketFactory.class", null);
int sfPort = -1;
try {
SocketFactory sf = getSocketFactory(sfClass);
if (sf != null) {
String sfPortStr =
props.getProperty(prefix + ".socketFactory.port", null);
if (sfPortStr != null) {
try {
sfPort = Integer.parseInt(sfPortStr);
} catch (NumberFormatException nfex) { }
}
// if port passed in via property isn"t valid, use param
if (sfPort == -1)
sfPort = port;
socket = createSocket(localaddr, localport,
host, sfPort, cto, sf, useSSL);
}
} catch (SocketTimeoutException sex) {
throw sex;
} catch (Exception ex) {
if (!fb) {
if (ex instanceof InvocationTargetException) {
Throwable t =
((InvocationTargetException)ex).getTargetException();
if (t instanceof Exception)
ex = (Exception)t;
}
if (ex instanceof IOException)
throw (IOException)ex;
IOException ioex = new IOException(
"Couldn"t connect using \"" + sfClass +
"\" socket factory to host, port: " +
host + ", " + sfPort +
"; Exception: " + ex);
ioex.initCause(ex);
throw ioex;
}
}
if (socket == null)
socket = createSocket(localaddr, localport,
host, port, cto, null, useSSL);
int to = -1;
if (timeout != null) {
try {
to = Integer.parseInt(timeout);
} catch (NumberFormatException nfex) { }
}
if (to >= 0)
socket.setSoTimeout(to);
configureSSLSocket(socket, props, prefix);
return socket;
}
public static Socket getSocket(String host, int port, Properties props,
String prefix) throws IOException {
return getSocket(host, port, props, prefix, false);
}
/**
* Create a socket with the given local address and connected to
* the given host and port. Use the specified connection timeout.
* If a socket factory is specified, use it. Otherwise, use the
* SSLSocketFactory if useSSL is true.
*/
private static Socket createSocket(InetAddress localaddr, int localport,
String host, int port, int cto,
SocketFactory sf, boolean useSSL)
throws IOException {
Socket socket;
if (sf != null)
socket = sf.createSocket();
else if (useSSL)
socket = SSLSocketFactory.getDefault().createSocket();
else
socket = new Socket();
if (localaddr != null)
socket.bind(new InetSocketAddress(localaddr, localport));
if (cto >= 0)
socket.connect(new InetSocketAddress(host, port), cto);
else
socket.connect(new InetSocketAddress(host, port));
return socket;
}
/**
* Return a socket factory of the specified class.
*/
private static SocketFactory getSocketFactory(String sfClass)
throws ClassNotFoundException,
NoSuchMethodException,
IllegalAccessException,
InvocationTargetException {
if (sfClass == null || sfClass.length() == 0)
return null;
// dynamically load the class
ClassLoader cl = getContextClassLoader();
Class clsSockFact = null;
if (cl != null) {
try {
clsSockFact = cl.loadClass(sfClass);
} catch (ClassNotFoundException cex) { }
}
if (clsSockFact == null)
clsSockFact = Class.forName(sfClass);
// get & invoke the getDefault() method
Method mthGetDefault = clsSockFact.getMethod("getDefault",
new Class[]{});
SocketFactory sf = (SocketFactory)
mthGetDefault.invoke(new Object(), new Object[]{});
return sf;
}
/**
* Start TLS on an existing socket.
* Supports the "STARTTLS" command in many protocols.
* This version for compatibility possible third party code
* that might"ve used this API even though it shouldn"t.
*/
public static Socket startTLS(Socket socket) throws IOException {
return startTLS(socket, new Properties(), "socket");
}
/**
* Start TLS on an existing socket.
* Supports the "STARTTLS" command in many protocols.
*/
public static Socket startTLS(Socket socket, Properties props,
String prefix) throws IOException {
InetAddress a = socket.getInetAddress();
String host = a.getHostName();
int port = socket.getPort();
//System.out.println("SocketFetcher: startTLS host " + host + ", port " + port);
try {
SSLSocketFactory ssf;
String sfClass =
props.getProperty(prefix + ".socketFactory.class", null);
SocketFactory sf = getSocketFactory(sfClass);
if (sf != null && sf instanceof SSLSocketFactory)
ssf = (SSLSocketFactory)sf;
else
ssf = (SSLSocketFactory)SSLSocketFactory.getDefault();
socket = ssf.createSocket(socket, host, port, true);
configureSSLSocket(socket, props, prefix);
} catch (Exception ex) {
if (ex instanceof InvocationTargetException) {
Throwable t =
((InvocationTargetException)ex).getTargetException();
if (t instanceof Exception)
ex = (Exception)t;
}
if (ex instanceof IOException)
throw (IOException)ex;
// wrap anything else before sending it on
IOException ioex = new IOException("Exception in startTLS: host " +
host + ", port " + port + "; Exception: " + ex);
ioex.initCause(ex);
throw ioex;
}
return socket;
}
/**
* Configure the SSL options for the socket (if it"s an SSL socket),
* based on the mail.<protocol>.ssl.protocols and
* mail.<protocol>.ssl.ciphersuites properties.
*/
private static void configureSSLSocket(Socket socket, Properties props,
String prefix) {
if (!(socket instanceof SSLSocket))
return;
SSLSocket sslsocket = (SSLSocket)socket;
String protocols = props.getProperty(prefix + ".ssl.protocols", null);
if (protocols != null)
sslsocket.setEnabledProtocols(stringArray(protocols));
else {
/*
* At least the UW IMAP server insists on only the TLSv1
* protocol for STARTTLS, and won"t accept the old SSLv2
* or SSLv3 protocols. Here we enable only the TLSv1
* protocol. XXX - this should probably be parameterized.
*/
sslsocket.setEnabledProtocols(new String[] {"TLSv1"});
}
String ciphers = props.getProperty(prefix + ".ssl.ciphersuites", null);
if (ciphers != null)
sslsocket.setEnabledCipherSuites(stringArray(ciphers));
/*
System.out.println("SSL protocols after " +
Arrays.asList(sslsocket.getEnabledProtocols()));
System.out.println("SSL ciphers after " +
Arrays.asList(sslsocket.getEnabledCipherSuites()));
*/
}
/**
* Parse a string into whitespace separated tokens
* and return the tokens in an array.
*/
private static String[] stringArray(String s) {
StringTokenizer st = new StringTokenizer(s);
List tokens = new ArrayList();
while (st.hasMoreTokens())
tokens.add(st.nextToken());
return (String[])tokens.toArray(new String[tokens.size()]);
}
/**
* Convenience method to get our context class loader.
* Assert any privileges we might have and then call the
* Thread.getContextClassLoader method.
*/
private static ClassLoader getContextClassLoader() {
return (ClassLoader)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
} catch (SecurityException ex) { }
return cl;
}
});
}
}
String based communication between Socket
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class BufferedSocketClient {
public static void main(String args[]) throws Exception {
Socket socket1;
int portNumber = 1777;
String str = "initialize";
socket1 = new Socket(InetAddress.getLocalHost(), portNumber);
BufferedReader br = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
PrintWriter pw = new PrintWriter(socket1.getOutputStream(), true);
pw.println(str);
while ((str = br.readLine()) != null) {
System.out.println(str);
pw.println("bye");
if (str.equals("bye"))
break;
}
br.close();
pw.close();
socket1.close();
}
}
///
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class BufferedSocketServer {
public static void main(String args[]) throws Exception {
int cTosPortNumber = 1777;
String str;
ServerSocket servSocket = new ServerSocket(cTosPortNumber);
System.out.println("Waiting for a connection on " + cTosPortNumber);
Socket fromClientSocket = servSocket.accept();
PrintWriter pw = new PrintWriter(fromClientSocket.getOutputStream(), true);
BufferedReader br = new BufferedReader(new InputStreamReader(fromClientSocket.getInputStream()));
while ((str = br.readLine()) != null) {
System.out.println("The message: " + str);
if (str.equals("bye")) {
pw.println("bye");
break;
} else {
str = "Server returns " + str;
pw.println(str);
}
}
pw.close();
br.close();
fromClientSocket.close();
}
}
Transfer a file via Socket
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws IOException {
ServerSocket servsock = new ServerSocket(123456);
File myFile = new File("s.pdf");
while (true) {
Socket sock = servsock.accept();
byte[] mybytearray = new byte[(int) myFile.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
sock.close();
}
}
}
The client module
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
public class Main {
public static void main(String[] argv) throws Exception {
Socket sock = new Socket("127.0.0.1", 123456);
byte[] mybytearray = new byte[1024];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("s.pdf");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
bos.close();
sock.close();
}
}
Use Socket to read and write stream
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
class SquareClient {
private final static int BUFSIZE = 20;
public static void main(String args[]) throws Exception {
String server = args[0];
int port = Integer.parseInt(args[1]);
double value = Double.valueOf(args[2]).doubleValue();
Socket s = new Socket(server, port);
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeDouble(value);
InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
value = dis.readDouble();
System.out.println(value);
s.close();
}
}
Write Double Using Sockets
// WriteDoubleUsingSockets - Client side that writes some objects to a stream
//
// Copyright (C) 1996 by Rinaldo Di Giorgio <rinaldo@digiorgio.ru>. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS"" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
import java.applet.Applet;
import java.awt.Label;
import java.io.DataOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Date;
/**
* Write some objects over the network to a remote server that reads the stream
* and procceds to save the objects to disk.
*/
public class WriteDoubleUsingSockets extends Applet {
DataOutputStream os = null;
ObjectOutput s = null;
int PortNumber = 2000;
String ServerName = "traveler";
/**
* Set the server and port name
*/
public void initMain(String s, int p) {
ServerName = s;
PortNumber = p;
init();
}
public void init() {
Date d = new Date();
// Get the portnumber and servername and allow to be called from a
// java main program also
try {
String param;
param = getParameter("PortNumber");
if (param != null)
PortNumber = Integer.parseInt(param);
param = getParameter("ServerName");
if (param != null)
ServerName = param;
} catch (NullPointerException e) { // Must be called from a main ignore
}
try {
Socket skt = new Socket(ServerName, PortNumber);
os = new DataOutputStream(skt.getOutputStream());
} catch (Exception e) {
Label l = new Label(e.toString());
add(l);
System.out.println(e);
return;
}
try {
s = new ObjectOutputStream(os);
} catch (Exception e) {
System.out.println(e);
System.out.println("Unable to open stream as an object stream");
}
try {
long startTime = System.currentTimeMillis();
for (int i = 0; i < 25; i++) {
s.writeObject(new Double(i));
}
os.close();
long endTime = System.currentTimeMillis() - startTime;
Label l = new Label("Writing 25 doubles server took: " + new Long(endTime).toString()
+ " milliseconds.");
add(l);
System.out.println("Object written");
} catch (Exception e) {
System.out.println(e);
System.out.println("Unable to write Objects");
}
}
// //////////////////////////////////////////////////////////////////////////
// Example of an applet and a main sharing code and be parameter
// driven.
// //////////////////////////////////////////////////////////////////////////
public static void main(String args[]) {
WriteDoubleUsingSockets showSavingAClassNet = new WriteDoubleUsingSockets();
if (args.length < 2) {
System.out.println("Usage: ServerName PortNumber");
System.exit(0);
} else {
String ServerName = new String(args[0]); // Notice local scope of
// ServerName and PortNumber
int PortNumber = Integer.parseInt(args[1]);
showSavingAClassNet.initMain(ServerName, PortNumber);
}
}
}
Write Objects From Socket
// WriteObjectsFromSocket - Read Objects from a Socket and save them
//
// Copyright (C) 1996 by Rinaldo Di Giorgio <rinaldo@digiorgio.ru>. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS"" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
/*
* Accept a connection and read some serialized
* data until the stream is closed. Once it is closed
* write the data to a disk file.
* This program always writes to /tmp/Object.
*/
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
*/
class WriteObjectsFromSocket {
public static void main(String args[]) {
Socket rs;
ServerSocket s;
int PortNumber = 2000; // Fixed port
boolean acceptLoop = true;
ReaderWriter readerwriter = null;
System.out.println("WriteFileFromSocket Running");
// ////////////////////////////////////////////////////////////////
// Open a socket on this server and listen for a connection
// Look for data if we get here that is requests
// ////////////////////////////////////////////////////////////////
try {
System.out.println("Waiting to accept connection");
s = new ServerSocket(PortNumber);
} catch (Exception e) {
System.out.println("Unable to open port" + PortNumber);
return;
}
while (acceptLoop) {
try {
rs = s.accept(); // Accept connections
} catch (Exception e) {
System.out.println("Accept failed port" + PortNumber);
return;
}
readerwriter = new ReaderWriter(rs); // Start a thread to read the input
}
}
}
/**
* Manage the writing of the file being read from a client
*/
class ReaderWriter extends Thread {
byte b[] = null;
int inputByte = 0;
String directory = null;
String filename = null;
DataInputStream is;
FileOutputStream localFile = null;
boolean writeloop = true;
ReaderWriter(Socket rs) {
// /////////////////////////////////////////////
// Open a remote stream to the client
// /////////////////////////////////////////////
try {
is = new DataInputStream(rs.getInputStream());
} catch (Exception e) {
System.out.println("Unable to get Stream");
return;
}
// /////////////////////////////////////////////
// Open the file that is to be written to
// /////////////////////////////////////////////
try {
File theFile = new File("/tmp", "Objects");
System.out.println("The file to be created or overwritten: " + theFile);
localFile = new FileOutputStream(theFile);
} catch (IOException e) {
System.out.println("Open error " + e);
return;
}
// ///////////////////////////////////////////
// Look for all the double data constantly
// ///////////////////////////////////////////
while (writeloop) {
// Look for data if we get here that is requests
try {
inputByte = is.readByte(); // Not the best way to do it
// Consider looking for available bytes
// and reading that amount.
} catch (IOException e) {
System.out.println("In the read loop:" + e);
writeloop = false;
}
// ///////////////////////////
// We did get something
// Write The Data
// ///////////////////////////
try {
localFile.write(inputByte);
} catch (IOException e) {
System.out.println("Write failed");
writeloop = false;
}
}
// ////////////////////////////////
// Close the connection and file
// ////////////////////////////////
try {
rs.close();
is.close();
localFile.close();
} catch (Exception e) {
System.out.println("Unable to close ");
}
System.out.println("Thread exiting");
}
}
Writing Text to a Socket
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] argv) throws Exception {
int port = 2000;
ServerSocket srv = new ServerSocket(port);
// Wait for connection from client.
Socket socket = srv.accept();
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
wr.write("aString");
wr.flush();
}
}
XML based message
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleSocketServer {
public static void main(String args[]) throws Exception {
ServerSocket serverSocket;
int portNumber = 1777;
Socket socket;
String str;
str = " <?xml version=\"1.0\" encoding=\"UTF-8\"?>";
str += "<ticketRequest><customer custID=\"1\">";
str += "</ticketRequest>";
serverSocket = new ServerSocket(portNumber);
System.out.println("Waiting for a connection on " + portNumber);
socket = serverSocket.accept();
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(str);
oos.close();
socket.close();
}
}
import java.io.ObjectInputStream;
import java.net.InetAddress;
import java.net.Socket;
public class SimpleSocketClient {
public static void main(String args[]) throws Exception {
Socket socket;
int portNumber = 1777;
String str = "";
socket = new Socket(InetAddress.getLocalHost(), portNumber);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
str = (String) ois.readObject();
System.out.println(str);
}
}
Zip socket
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import java.net.Socket;
class ZipSocket extends Socket {
private InputStream in;
private OutputStream out;
public ZipSocket() { super(); }
public ZipSocket(String host, int port)
throws IOException {
super(host, port);
}
public InputStream getInputStream()
throws IOException {
if (in == null) {
in = new ZipInputStream(super.getInputStream());
}
return in;
}
public OutputStream getOutputStream()
throws IOException {
if (out == null) {
out = new ZipOutputStream(super.getOutputStream());
}
return out;
}
public synchronized void close() throws IOException {
OutputStream o = getOutputStream();
o.flush();
super.close();
}
}