本帖最后由 yangcy 于 2014-7-13 16:56 编辑
客户端代码:
- public class TcpClient {
- public static void main(String[] args) throws UnknownHostException,
- IOException {
- //创建一个客户端Socket
- Socket s = new Socket(InetAddress.getLocalHost().getHostAddress(), 8888);
- //读取键盘中输入的字符串
- Scanner sc = new Scanner(System.in);
- String line = sc.nextLine();
- //获取客户端输出流,将从键盘中读到的字符串写入输出流
- OutputStream os = s.getOutputStream();
- os.write(line.getBytes());
- //创建客户端输入流,将从服务端返回的内容打印到控制台
- InputStream in = s.getInputStream();
- byte[] buf = new byte[1024];
- int len = in.read(buf);
- System.out.println(new String(buf, 0, len));
- s.close();
- }
- }
复制代码 服务端代码:
- public class TcpServer {
- public static void main(String[] args) {
- ServerSocket ss = null;
- Socket s = null;
- InputStream in = null;
- OutputStream out = null;
- try {
- //创建一个服务端Socket
- ss = new ServerSocket(8888);
- //接收客服端的Socket
- s = ss.accept();
- //获取客服端输入流
- in = s.getInputStream();
- //创建一个StringBuilder容器
- StringBuilder sb = new StringBuilder();
- //创建一个直接数组,将读到的字节存入数组中
- byte[] buf = new byte[1024];
- int len = -1;
- while((len = in.read(buf))!=-1){
- //将数组转换成字符串,存入StringBuilder容器中
- sb.append(new String(buf, 0, len));
- }
- //将容器中的字符串反转
- sb.reverse();
- //创建一个客户端输出流
- out = s.getOutputStream();
- out.write(sb.toString().getBytes());
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- s.close();
- ss.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
复制代码
客户端发数据了,服务端怎么接收不到数据啊。郁闷啊。
|
|