该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
客户端
@Test
public void client(){
Socket socket =null;
OutputStream o =null;
InputStream i =null;
try {
socket = new Socket(InetAddress.getByName("192.168.1.104"),9090);
o = socket.getOutputStream();
o.write("我是客户端".getBytes());
socket.shutdownOutput();
i = socket.getInputStream();
byte[] b=new byte[20];
int len;
while((len = i.read(b)) !=-1){
String str=new String(b, 0, len);
System.out.print(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(i !=null){
try {
i.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(o !=null){
try {
o.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 o = null;
try {
ss = new ServerSocket(9090);
s = ss.accept();
is = s.getInputStream();
byte[] b = new byte[20];
int len;
while((len =is.read(b)) != -1){
String str=new String(b,0,len);
System.out.print(str);
}
o = s.getOutputStream();
o.write("我已收到".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(o !=null){
try {
o.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();
}
}
}
}