socket - софтуерна абстракция за представяне на двата
"терминала" за връзка между машините.
ServerSocket - свързва програмата сървър със
съответния порт, слуша мрежата.
Socket - използван от програмата клиент за
свързване със сървъра и обмен на информация. Използвана от програмата
сървър за обмен на информация след установяването на връзка.
процедури в програмата сървър:
Пример 2:Един прост сървър и клиент:
public class FirstServer {
// Choose a port outside of the range 1-1024:
public static final int PORT = 8080;
public static void main(String[] args)
throws IOException {
ServerSocket s = new ServerSocket(PORT);
System.out.println("Started: " + s);
try {
// Blocks until a connection occurs:
Socket socket = s.accept();
try
{
//
System.out.println(
"Connection
accepted: "+ socket);
BufferedReader in =
new
BufferedReader(
new InputStreamReader(
socket.getInputStream()));
// Output is
automatically
flushed
// by PrintWriter:
PrintWriter out =
new
PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())),true);
while (true) {
String str
= in.readLine();
if
(str.equals("END"))
break;
System.out.println("Echoing:
" + str);
out.println(str);
}
// Always close the two sockets...
} finally {
System.out.println("closing...");
socket.close();
}
} finally {
s.close();
}
}
}
//Very simple client that just sends
//lines to the server and reads lines
//that the server sends.
import java.net.*;
import java.io.*;
public class FirstClient {
public static void main(String[] args)throws IOException {
// Passing null to getByName() produces the
// special "Local Loopback" IP address, for
// testing on one machine w/o a network:
// Alternatively, you can use
// the address or name:
// InetAddress addr = InetAddress.getByName("127.0.0.1");
// InetAddress addr = InetAddress.getByName("localhost");
String server = null;
InetAddress addr = InetAddress.getByName(server);
System.out.println("addr = " + addr);
Socket socket = new Socket(addr, FirstServer.PORT); //Socket s=new Socket(); // Guard everything in a try-finally to make //s.connect(new InetSocketAddress(host,port),timeout); // sure that the socket is closed: try { System.out.println("socket = " + socket); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream())); BufferedReader sin = new BufferedReader( new InputStreamReader(System.in)); // Output is automatically flushed // by PrintWriter: PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream())),true); for(int i = 0; i <10 ; i ++) { System.out.print("input a line [empty for finish] " + i + ":"); String s = sin.readLine(); if(s.length()==0) break; out.println(i + ": " +s); String str = in.readLine(); System.out.println(str); } out.println("END"); } finally { System.out.println("closing..."); socket.close(); } } }
>java
FirstServer Started: ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=8080] Connection accepted: Socket[addr=127.0.0.1/127.0.0.1,port=1029,localport=8080] Echoing: first line :0 Echoing: second line :1 Echoing: third line :2 closing... |
>java FirstClient
addr = localhost/127.0.0.1 socket = Socket[addr=localhost/127.0.0.1,port=8080,localport=1033] input a line [empty for finish] 0: first line :0 input a line [empty for finish] 1: second line :1 input a line [empty for finish] 2: third line :2 input a line [empty for finish] 3: closing... |
//: MultiClientServer.java
// A server that uses multithreading to handle
// any number of clients.
import java.io.*;
import java.net.*;
class ServeOneClient extends Thread {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public ServeOneClient(Socket s) throws
IOException {
socket = s;
in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
// Enable auto-flush:
out = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream()
)
),
true);
// If any of the above calls throw an
// exception, the caller is responsible for
// closing the socket. Otherwise the thread
// will close it.
start();
// Calls run()
}
public void run() {
try {
while (true) {
String str = in.readLine();
if (str.equals("END")) break;
System.out.println("Echoing: " + str);
out.println(str);
}
System.out.println("closing...");
} catch (IOException e) { }
finally {
try {
socket.close();
} catch(IOException e) {}
}
}
}
public class MultiClientServer {
static final int PORT = 8080;
public static void main(String[] args) throws IOException
{
ServerSocket s = new ServerSocket(PORT);
System.out.println("Server Started");
try {
while(true) {
// Blocks until a
connection
occurs:
Socket socket =
s.accept();
try {
new
ServeOneClient(socket);
} catch(IOException e)
{
// If it
fails, close the socket,
// otherwise
the thread will close it:
socket.close();
}
}
} finally {
s.close();
}
}
}
Клиенти с име:
// Client with name
import java.net.*;
import java.io.*;
public class ClientWithName {
public static void main(String[] args)throws IOException {
// Passing null to getByName() produces the
// special "Local Loopback" IP address, for
// testing on one machine w/o a network:
// Alternatively, you can use
// the address or name:
// InetAddress addr =
InetAddress.getByName("127.0.0.1");
// InetAddress addr =
InetAddress.getByName("localhost");
String server = null;
InetAddress addr = InetAddress.getByName(server);
System.out.println("addr = " + addr);
Socket socket = new Socket(addr, FirstServer.PORT);
// Guard everything in a try-finally to make
// sure that the socket is closed:
try {
System.out.println("socket = " + socket);
BufferedReader sin = new BufferedReader(
new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
//
Output is automatically flushed
//
by PrintWriter:
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),true);
System.out.print("Your name: ");
String name = sin.readLine();
for(int i = 0; i <10 ; i ++) {
System.out.println("input a line [empty for finish] :");
String s = sin.readLine();
if(s.length()==0) break;
out.println(name+":"+s);
String str = in.readLine();
System.out.println(str);
}
out.println("END");
} finally {
System.out.println("closing...");
socket.close();
}
}