TCP,UDP通信をSocketで実現
TCP,UDP通信をSocketで実現
SocketによるUDP通信
UDPは、少量のデータのみを一度に伝送し、信頼性に対する要求が低いアプリケーション環境に適しています.
public class UDPServer {
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket();
byte[] buffer = "udp test".getBytes();
DatagramPacket dp = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("localhost"), 8000);
// localhost 255.255.255.255 ,
ds.send(dp);
ds.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class UDPClient {
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket(8000);
byte[] buffer = new byte[1024];
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(), 0, dp.getLength());
int port = dp.getPort();
System.out.println("ip: " + ip + "; data: " + data + "; port: " + port);
ds.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
SocketによるTCP通信
TCPは3回の「会話」を経なければならないため、伝送が信頼でき、大きなファイルの伝送に適しており、UDPよりも速度が遅い.
public class TCPServer {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(8001);
boolean flag = true;
while (flag) {
final Socket client = server.accept();
System.out.println("Connect to client " + client + " remote add: " + client.getRemoteSocketAddress());
new Thread(new Runnable() {
@Override
public void run() {
try {
PrintStream ps = new PrintStream(client.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
while (true) {
String line = br.readLine();
System.out.println("client: " + line);
ps.println(line + " copied");
if ("bye".equals(line)) {
break;
}
}
ps.close();
br.close();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class TCPClient {
public static void main(String[] args) {
try {
Socket client = new Socket("localhost", 8001);
client.setSoTimeout(10000);
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
PrintStream out = new PrintStream(client.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
while (true) {
System.out.print("input: ");
String str = input.readLine();
out.println(str);
if ("bye".equals(str)) {
break;
}
String read = br.readLine();
System.out.println("server: " + read);
}
input.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}