码迷,mamicode.com
首页 > 其他好文 > 详细

TCP练习2: 客户端给服务端发送文本,服务端将文本转成大写再返回给客户端

时间:2015-05-08 14:53:59      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:socket   java   tcp   服务器   

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

}

TCP练习2: 客户端给服务端发送文本,服务端将文本转成大写再返回给客户端

标签:socket   java   tcp   服务器   

原文地址:http://blog.csdn.net/motianlundejiyi/article/details/45579629

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!