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();
}
}
}
}

}

    推荐阅读