пример сервера на сокетах

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package ru.rpod.taop._16;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String args[]) {
Socket client = null;
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(3456);
System.out.println("Waiting...");
do{
client = serverSocket.accept();
System.out.println("Client connected...");
InputStream is = client.getInputStream();
byte[] bytes = new byte[18];
is.read(bytes);
System.out.println("Server get information: "+new String(bytes));
OutputStream os = client.getOutputStream();
bytes = "Hello from serer".getBytes();
os.write(bytes);
is.close();
os.close();
}
while(true);
} catch (IOException e) {
e.printStackTrace();
}
finally{
try{
if(client!=null) client.close();
if(serverSocket!=null) serverSocket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}