@Test//
public void Client(){
Socket socket= null;
OutputStream outputStream=null;
try {
socket=new Socket(InetAddress.getByName("175.159.70.105"),9292);//创建socket对象,通过构造器指明服务器的IP地址,端口号
outputStream=socket.getOutputStream();//发送数据
outputStream.write("客户端".getBytes());
}catch (IOException e){
e.printStackTrace();
}finally {//关闭流及socket
if(outputStream!=null){
try {
outputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
if(socket!=null){
try{
socket.close();
}catch (IOException E){
E.printStackTrace();
}
}
}
}
@Test//
public void server(){
ServerSocket serverSocket=null;
Socket s=null;
InputStream is=null;
try {
serverSocket=new ServerSocket(9292);//创建ServerSockett对象及端口号
s=serverSocket.accept();//返回一个Socket对象
is=s.getInputStream();//接收文件
byte[] b=new byte[15];
int len;
while((len=is.read(b))!=-1){
String str=new String(b,0,len);
System.out.println(str);
}
System.out.println("收到来自于"+s.getInetAddress().getHostAddress()+"的文件");
}catch (IOException E){
E.printStackTrace();
}finally {
if(is!=null){
try {
is.close();
}catch (IOException E){
E.printStackTrace();
}
}
if(s!=null){
try {
s.close();
}catch (IOException E){
E.printStackTrace();
}
}
if(serverSocket!=null){
try {
serverSocket.close();
}catch (IOException E){
E.printStackTrace();
}
}
}
}
}
客户给服务端发送信息,服务端输出此信息在服务台上
客户端
收到来自于175.159.70.105的文件