已有258人关注
TCP的数据传输问题
发表在Java答疑区 2017-07-18
是否精华
版块置顶:

package cn.innet.demo.tcp.touppdate;


import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.Socket;

import java.net.UnknownHostException;


public class Client {

public static void main(String[] args) throws UnknownHostException, IOException {

Socket socket = new Socket("192.168.0.100", 8888);

BufferedReader key_bufr = new BufferedReader(new InputStreamReader(System.in));

BufferedWriter socket_bufw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

BufferedReader socket_bufr = new BufferedReader(new InputStreamReader(socket.getInputStream()));

String line = null;

System.out.println("连接成功");

while((line = key_bufr.readLine())!=null){

if("over".equals(line)){

break;

}

System.out.println("读取到的:"+line);

socket_bufw.write(line);

System.out.println("已写出");

socket_bufw.flush();

System.out.println("已刷新");

System.out.println(socket_bufr.readLine());

}

socket.close();

}


}

===========================================================

package cn.innet.demo.tcp.touppdate;


import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.ServerSocket;

import java.net.Socket;


public class Server {

public static void main(String[] args) throws IOException {

ServerSocket serverSocket = new ServerSocket(8888);

Socket socket = serverSocket.accept();

String ip = socket.getInetAddress().getHostAddress();

System.out.println(ip+"......connected");

BufferedReader socket_bufr = new BufferedReader(new InputStreamReader(socket.getInputStream()));

BufferedWriter socket_bufw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

String line = null;

System.out.println("等待读取网络流数据");

while((line = socket_bufr.readLine())!=null){

System.out.println(line);

socket_bufw.write(line.toUpperCase());

socket_bufw.flush();

}

serverSocket.close();

socket.close();

}

}

============================================================

为什么我的客户端写的数据服务端接收不到啊  客户端卡在"已刷新",服务端卡在"等待读取网络流数据".....我明明是从客户端把数据写到网络流里  然后服务端那边去接收的呀

分享到:
精彩评论 1
根号申
学分:4736 LV12
TA的每日心情
2021-07-16 23:48:46
2017-07-19
沙发

把字符流都改回字节流,因为双方都是用readLine()读取流中字符串,但此方法是按行读取,需要数据末尾有换行符,否则就始终处于读取的状态。

首页上一页 1 下一页尾页 1 条记录 1/1页
手机同步功能介绍
友情提示:以下图书配套资源能够实现手机同步功能
明日微信公众号
明日之星 明日之星编程特训营
客服热线(每日9:00-17:00)
400 675 1066
mingrisoft@mingrisoft.com
吉林省明日科技有限公司Copyright ©2007-2022,mingrisoft.com, All Rights Reserved长春市北湖科技开发区盛北大街3333号长春北湖科技园项目一期A10号楼四、五层
吉ICP备10002740号-2吉公网安备22010202000132经营性网站备案信息 营业执照