TCP练习2( 客户端给服务端发送文本,服务端将文本转成大写再返回给客户端)
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import org.junit.Test;
/*
* 客户端给服务端发送文本,服务端将文本转成大写再返回给客户端
*/
public class TCPExer2 {
/*
* 客户端
*/
@Test
public void client(){
Socket socket = null;
OutputStream os = null;
InputStream is = null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
os = socket.getOutputStream();
os.write("abcdefght".getBytes());
socket.shutdownOutput();
is = socket.getInputStream();
byte[] b = new byte[1024];
int len;
while((len = is.read(b)) != -1){
String str = new String(b,0,len);
System.out.println("我是客户端,接收到来自服务端的返回数据:" + str);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is != null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(os != null){
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/*
* 服务端
*/
@Test
public void server(){
ServerSocket ss = null;
Socket s = null;
InputStream is = null;
OutputStream os = null;
try {
ss = new ServerSocket(9999);
s = ss.accept();
is = s.getInputStream();
byte[] b = new byte[1024];
int len;
String str = null;
while((len = is.read(b)) != -1){
str = new String(b,0,len);
System.out.println("我是服务端,收到客户端的信息:" + str);
str = str.toUpperCase();
}
s.shutdownInput();
os = s.getOutputStream();
os.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(os != null){
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(is != null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(s != null){
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ss != null){
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
推荐阅读
- CVE-2020-16898|CVE-2020-16898 TCP/IP远程代码执行漏洞
- 【生信技能树】R语言练习题|【生信技能树】R语言练习题 - 中级
- Python基础|Python基础 - 练习1
- 呼吸练习心得
- 2018-04-16动画练习作业
- 一组水彩小练习
- 《简社》绝句练习之九
- 写作若是有了长期的练习,往后自然就可以了
- 2021—3—8日教练实践总结&呼吸练习&觉察日记
- 练习钢笔字335弹——积,欢迎围观参与|练习钢笔字335弹——积,欢迎围观参与|硬笔书法练习