网络通信3

//2.客户端给服务器端发送文本,服务器端转成大写在返回给客户端

package cn.wang;

import static org.junit.Assert.*;

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 java.util.Scanner;

import org.junit.Test;
//2.客户端给服务器端发送文本,服务器端转成大写在返回给客户端
public class Testip2 {

@Test
public void client() throws Exception {
Scanner sac=new Scanner(System.in);
//建立一个Socket,通过构造器指明服务器的IP地址,以及接受程序的端口
Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),9988);
//发送数据
OutputStream os=socket.getOutputStream();
System.out.println("请输入字符");
String str=sac.next();
os.write(str.getBytes());//转化为字节
socket.shutdownOutput();//提示完成输出
//接受服务段的数据
InputStream is=socket.getInputStream();
byte[] b=new byte[1024];
int len;
while((len=is.read(b))!=-1){
String str1=new String(b,0,len);
System.out.println(str1);
}
is.close();
sac.close();
os.close();
socket.close();


}


@Test
public void servet() throws Exception {
//1.建立一个ServerSocket的对象,通过构造器指明自身的端口号
ServerSocket soc=new ServerSocket(9988);
//调用对象accept
Socket ss=soc.accept();
//对获取的的输入的流操作
InputStream is=ss.getInputStream();
byte[] bb=new byte[20];
int length;
String str=new String();
while((length=is.read(bb))!=-1){
String str1=new String(bb,0,length);
str+=str1;

}
String str2=str.toUpperCase();// 将字符转化为大写。
OutputStream oos=ss.getOutputStream();
oos.write(str2.getBytes());
//关流
oos.close();
is.close();
ss.close();
soc.close();


}
}

猜你喜欢

转载自www.cnblogs.com/liuchunyong/p/10403235.html