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

tcp

时间:2017-05-23 11:12:33      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:catch   new   UI   while   nbsp   shang   client   ddr   服务端   

服务端

/**
*
*/
package com.atguigu.exer;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.junit.Test;

/**
*方法说明
* @author shanghaitao
* @since 2017年5月2日
*/
public class Sserver {
public static void main(String[] args) {

}
@Test
public void testServer() {
System.out.println("这是服务端");
Socket s = null;
ServerSocket ss = null;
InputStream is = null;
OutputStream os = null;
try {
ss = new ServerSocket(9999);
s = ss.accept();
String str = null;
byte [] b = new byte[10];
int len ;
is = s.getInputStream();
while((len = is.read(b))!=-1){
str += new String(b, 0, len);
System.out.println(str);
}
os = s.getOutputStream();
os.write("我已收到你的信息".getBytes());

} catch (Exception e) {
e.printStackTrace();
}finally {
if(os!=null){
try {
os.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if(is!=null){
try {
is.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if(s!=null){
try {
s.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if(ss!=null){
try {
ss.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}

}
}

客户端

/**
*
*/
package com.atguigu.exer;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

import org.junit.Test;

/**
*方法说明
* @author shanghaitao
* @since 2017年5月2日
*/
public class Cllient {
public static void main(String[] args) {

}
@Test
public void TestClient() {
System.out.println("这是客户端");
Socket socket = null;
InputStream is = null;
OutputStream os = null;

try {
socket = new Socket(InetAddress.getLocalHost(), 9999);
is = socket.getInputStream();
os = socket.getOutputStream();
os.write("我是客户端".getBytes());
socket.shutdownOutput();
String str = null;
byte b [] = new byte[10];
int len ;
while((len = is.read(b))!=-1){
str += new String(b,0,len) ;
System.out.println(str);
}


} catch (Exception e) {
e.printStackTrace();
}finally {
if(is !=null){
try {
is.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if(os !=null){
try {
os.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if(socket !=null){
try {
socket.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}

}
}

 

输出

这是客户端
null我已收到你
null我已收到你的信息

这是服务端
null我是客户端

tcp

标签:catch   new   UI   while   nbsp   shang   client   ddr   服务端   

原文地址:http://www.cnblogs.com/taz372436/p/6892879.html

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