计算机网络-自顶向下 udp,tcp套接字编程 Java版
io异常处理均是throws,更应该改为try-catch形式
UDP客户服务端 udp以数据包的形式传输,而且是无连接的,所以每次传输均需指明对方端口和IP
DatagramSocket clientSocket=new DatagramSocket(8888);
Scanner scan=new Scanner(System.in);
System.out.println("input lowercase sentence:");
String str=scan.nextLine();
byte [] bytes=str.getBytes();
InetAddress serverIP=InetAddress.getLocalHost();
DatagramPacket sendPacket=new DatagramPacket(bytes,0,bytes.length,serverIP,6688);
clientSocket.send(sendPacket);
byte [] bytes1=new byte[1024];
DatagramPacket recPacket=new DatagramPacket(bytes1,0,bytes.length);
clientSocket.receive(recPacket);
String upstr=new String(recPacket.getData(),0,recPacket.getLength());
System.out.println(upstr);
clientSocket.close();
DatagramSocket serverSocket=new DatagramSocket(6688);
byte [] bytes1=new byte[1024];
byte [] bytes2;
DatagramPacket recpacket=new DatagramPacket(bytes1,0,bytes1.length);
while (true){
serverSocket.receive(recpacket);
InetAddress clientIP=recpacket.getAddress();
int clientPort=recpacket.getPort();
String str=new String(recpacket.getData(),0,recpacket.getLength());
String upstr=str.toUpperCase();
bytes2=upstr.getBytes();
DatagramPacket sendPacket=new DatagramPacket(bytes2,0,bytes2.length,clientIP,clientPort);
serverSocket.send(sendPacket);
TCP客户服务端 tcp是需要建立连接的,连接建立后便可顺着连接进行全双工传输,连接建立后两个主机之间类似形成io流,可通过各自套接字获取输入,输出流。注意点是tcp服务端有一个面向所有客户的套接字用于建立连接,还有为每个客户单独分配的套接字用于传输数据
Socket socket =new Socket(InetAddress.getLocalHost(),9898);
OutputStream o =socket.getOutputStream();
Scanner scan=new Scanner(System.in);
System.out.println("input lowercase sentence:");
String str=scan.nextLine();
o.write(str.getBytes());
socket.shutdownOutput();
InputStream i=socket.getInputStream();
byte [] bytes=new byte[1024];
int len;
while ((len=i.read(bytes))!=-1){
System.out.println(new String(bytes,0,len));
}
i.close();
o.close();
socket.close();
ServerSocket serverSocket=new ServerSocket(9898);
while (true){
Socket newsocket=serverSocket.accept();
InputStream inputStream=newsocket.getInputStream();
byte[] bytes=new byte[1024];
int len;
while ((len=inputStream.read(bytes))!=-1){
String upstr=new String(bytes,0,len).toUpperCase();
OutputStream outputStream=newsocket.getOutputStream();
outputStream.write(upstr.getBytes());
outputStream.close();
}
inputStream.close();
newsocket.close();
}
|