您的位置:首页 > 其它

一个客户端和一个服务器的多次通信

2017-05-05 16:41 351 查看
package com.forward.date20170505.one_to_oneformany;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
* @Description: 客户端类,一个客户端和一个服务器的多次通信
* @author forward
* @date 2017年5月5日 下午11:17:14
* @version V2.0
*/
public class Client {
public static void main(String[] args) {
OutputStream os = null;
InputStream is = null;
Socket s = null;
Scanner input = new Scanner(System.in);
String str = null;
int count = 0;
try {
System.out.println("客户端");
// 1、创建Socket套接字 //流套接字
s = new Socket("127.0.0.1", 1766);

while(!"q".equals(str)){
// 2、一个客户端和一个服务器的多次交互
System.out.println("一个客户端和一个服务器的第"+(++count)+"次交互");
System.out.println("客户端发送:(q结束交互)");
str = input.next();
// 2-1写数据到服务端
os = s.getOutputStream();
byte[] osBuf = str.getBytes();
os.write(osBuf);

// 2-2从服务端读数据
is = s.getInputStream();
byte[] isBuf = new byte[512];
int index = is.read(isBuf);
System.out.println("客户端接收:" + new String(isBuf, 0, index));
}

// 3、关闭连接
System.out.println("客户端断开连接!");
os.close();
is.close();
s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}
package com.forward.date20170505.one_to_oneformany;

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

/**
* @Description: 服务端,一个客户端和一个服务器的多次通信
* @author forward
* @date 2017年5月5日 上午11:40:47
* @version V2.0
*/

public class Server {
public static void main(String[] args) {
ServerSocket listener = null;
Socket s = null;
InputStream is = null;
OutputStream os = null;
String str = null;
int count = 0;

try {
// 1、创建服务器套接字 创建一个ServerSocket类,同时在运行该语句的计算机的指定端口处建立一个监听服务
listener = new ServerSocket(1766);

// 2、创建新套接字 并返回一个用于与该Client通信的Socket对象Link-SocketServer程序
// ServerSocket 进行accept之后,就将主动权转让了。该Socket对象绑定了客户程序的IP地址或端口号。
System.out.println("服务端等待连接中。。。");
s = listener.accept();

while(!"q".equals(str)){
// 3、Server程序只要向这个Socket对象读写数据,就可以实现向远端的Client读写数据
// 3、一个客户端和一个服务器的多次交互
System.out.println("一个客户端和一个服务器的第"+(++count)+"次交互");

// 3-1从客户端读数据
is = s.getInputStream();
byte[] isBuf = new byte[512];
int index = is.read(isBuf);
str = new String(isBuf, 0, index);
System.out.println("服务器接收:" +str);

// 3-2写数据到客户端
os = s.getOutputStream();
byte[] osBuf = "我已收到".getBytes();
System.out.println("服务器发送:"+new String(osBuf,0,osBuf.length));
os.write(osBuf);
}
// 4、断开连接
Syst
9bda
em.out.println("服务器端断开连接!");
is.close();
os.close();
s.close();
listener.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: