导航
  • 全部
...

关于Socket编程的输入流(高手来啊)

zhucg518 2006-09-15 12:38:29
程序如下:
Socket socket = new Socket(host,port);
InputStream is = socket.getInputStream();
int c = 0;
StringBuffer sb = new StringBuffer();
while((c = is.read()) != -1) {
sb.append((char)c);
}
System.out.println("receive string is " + sb.toString());

程序运行不到System.out.println("receive string is " + sb.toString());
好象在is.read()的时候就不动了。

这段程序代码InputStream要读取以下内容(我用sniffer截取的数据)
01 5e 09 d5 bc 32 98 79 5c f0 00 0a 50 10 43 cd 7c 08 00 00
...全文
给本帖投票
1189 22 打赏 收藏 转发到动态 举报
写回复
用AI写文章
22 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhucg518 2006-09-30
  • 打赏
  • 举报
回复
问题已经解决!~
mdxk 2006-09-19
  • 打赏
  • 举报
回复
代码好像是1.5的
我说怎么过不去那
呵呵
TinyJimmy 2006-09-16
  • 打赏
  • 举报
回复
socket通信有通信的规则, 如果你希望保持长连接, 就应该有个通信协议, 包括写入\0也是规则的一部分, 传完一个文件等待下一个. 要可不保持长连接, 可使用webservice, 这样你的协议变的更为可读, 更容易包装成产品.

看你的程序希望read结束, 不象是希望保持长连接的样子, 晕ing
zhucg518 2006-09-15
  • 打赏
  • 举报
回复
wmzsl(王明哲)
我连的服务器不是java的服务器,是用c写的
我市以下你写的客户端阿
wmzsl 2006-09-15
  • 打赏
  • 举报
回复
免费再送你一个非阻塞的高级server

package server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class NonBlockingServer {

private Selector selector;

private ServerSocketChannel server;

private int port = 8000;

private long connectionsNum = 0l;

private long errorsNum = 0l;

private ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1000, 1000,
60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

public NonBlockingServer() {
threadPool.prestartAllCoreThreads();
System.out.println("Inside default ctor");
}

public NonBlockingServer(int port) {
threadPool.prestartAllCoreThreads();
System.out.println("Inside the other ctor");
this.port = port;
}

public void initializeOperations() throws IOException {
System.out.println("Inside initialization");
selector = Selector.open();
server = ServerSocketChannel.open();
server.configureBlocking(false);
InetSocketAddress isa = new InetSocketAddress(port);
server.socket().bind(isa);
System.out.println("Accepting connections on port "
+ server.socket().getLocalPort());
}

public void startServer() {

System.out.println("Inside startserver");
try {
initializeOperations();
} catch (Exception e) {
e.printStackTrace();
return;
}

System.out.println("Abt to block on select()");
try {
SelectionKey acceptKey = server.register(selector,
SelectionKey.OP_ACCEPT);
} catch (ClosedChannelException e) {
e.printStackTrace();
return;
}

while (true) {
try {
// this may block for a long time, upon return the
// selected set contains keys of the ready channels
int n = selector.select();

if (n == 0) {
continue; // nothing to do
}

// get an iterator over the set of selected keys
Iterator it = selector.selectedKeys().iterator();

// look at each key in the selected set
while (it.hasNext()) {
SelectionKey key = (SelectionKey) it.next();

// remove key from selected set, it's been handled
it.remove();

// Is a new connection coming in?
if (key.isAcceptable()) {
ServerSocketChannel ssc = (ServerSocketChannel) key
.channel();

SocketChannel socketChannel = ssc.accept();

registerChannel(selector, socketChannel,
SelectionKey.OP_READ);

connectionsNum++;
System.out.println("Connection established with "
+ socketChannel);
System.out.println("******connectionsNum:"
+ connectionsNum + "******");
System.out.println("******errorNum:" + errorsNum
+ "******");
}

// is there data to read on this channel?
if (key.isReadable()) {
key.interestOps(key.interestOps()
& (~SelectionKey.OP_READ));
Task task = new Task(key);
threadPool.execute(task);
}
}
} catch (Exception e) {
e.printStackTrace();
selector.wakeup();
errorsNum++;
}
}
}

/**
* Register the given channel with the given selector for the given
* operations of interest
*/
protected void registerChannel(Selector selector,
SelectableChannel channel, int ops) throws Exception {
if (channel == null) {
return; // could happen
}

// set the new channel non-blocking
channel.configureBlocking(false);

// register it with the selector
channel.register(selector, ops);
}

class Task implements Runnable {
SelectionKey key = null;

public Task(SelectionKey key) {
this.key = key;
}

public void run() {
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(2048);
int count;
buffer.clear();

try {
Thread.sleep(5000);
buffer.clear();
while ((count = (socketChannel.read(buffer))) > 0) {
buffer.flip();
while (buffer.hasRemaining()) {
socketChannel.write(buffer);
}
buffer.clear();
}

if (count < 0) {
try {
socketChannel.close();
return;
} catch (Exception e) {
e.printStackTrace();
}
}

// resume interest in OP_READ
key.interestOps(key.interestOps() | SelectionKey.OP_READ);

// cycle the selector so this key is active again
key.selector().wakeup();

} catch (Exception e) {
e.printStackTrace();
System.out.println("Caught '" + e + "' closing channel");

// close channel and nudge selector
try {
socketChannel.close();
} catch (IOException ex) {
ex.printStackTrace();
}

key.selector().wakeup();
key = null;
errorsNum++;
}
}
}

public static void main(String args[]) {
NonBlockingServer nbs = new NonBlockingServer();
nbs.startServer();
}
}
zhucg518 2006-09-15
  • 打赏
  • 举报
回复
你的意思我试过了,好象还是不行
byte[] b = new byte[1024];
is.read(b);
System.out.println(b.length);
程序还是执行到is.read(b);
后面的System.out.println(b.length);
就不执行了。
wmzsl 2006-09-15
  • 打赏
  • 举报
回复
客户端程序:
package client;

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.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Client {

private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(100, 100, 60,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
private static int successCount=0;

/**
* @param args
*/
public static void main(String[] args){

String hostname = "192.168.2.34";

if (args.length > 0) {
hostname = args[0];
}

for(int i=0;i<=1000;i++){
Process p = new Process(hostname);
//threadPool.execute(p);
Thread thread = new Thread(p);
thread.start();
}
}

static class Process implements Runnable{

String hostname=null;
public Process(String hostname){
this.hostname = hostname;
}

public void run() {
BufferedWriter out = null;
BufferedReader in = null;
Socket connection = null;

try {
long start = System.currentTimeMillis();
Thread.sleep(200);
connection = new Socket(hostname, 8000);
in = new BufferedReader(new InputStreamReader(connection
.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));

StringBuffer sb = new StringBuffer();
for(int i=0;i<2044;i++){
sb.append("a");
}

out.write(sb.toString());
out.write("\r\n\r\n");
out.flush();
System.out.println(in.readLine());
System.out.println("*********************"+((System.currentTimeMillis() - start)/1000));
System.out.println("********successCount:"+(++successCount)+"********");

}
catch (Exception e) {
System.err.println(e);
} finally {
try {
if (in != null)
in.close();
if (out != null)
out.close();
if (connection != null)
connection.close();
} catch (IOException e) {
}
}
}
}
}


不过要用jdk1.5以上版本
wmzsl 2006-09-15
  • 打赏
  • 举报
回复
估计你是没有读到数据!

服务器程序

package server;

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;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class BlockingServer {

private int port = 8000;

private long connectionsNum = 0l;
private long errorsNum = 0l;

private ThreadPoolExecutor threadPool = new ThreadPoolExecutor(100, 100, 60,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

public BlockingServer(int port) {
this.port = port;
}

public BlockingServer() {
}

public void start() {
try {
ServerSocket server = new ServerSocket(port);
Socket connection = null;
System.out.println("Accepting connections on port "
+ server.getLocalPort());
while (true) {
try {
connection = server.accept();
Task task = new Task(connection);
threadPool.execute(task);

connectionsNum++;
System.out.println("Connection established with "
+ connection);
System.out.println("******connectionsNum:" + connectionsNum
+ "******");
System.out.println("******errorNum:" + errorsNum
+ "******");
} catch (IOException ex) {
ex.printStackTrace();
errorsNum++;
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

class Task implements Runnable {
Socket connection = null;

public Task(Socket connection) {
this.connection = connection;
}

public void run() {
BufferedWriter out = null;
BufferedReader in = null;
try {
Thread.sleep(5000);
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(
connection.getOutputStream()));

String readString = in.readLine();

out.write(readString);
out.write("\r\n\r\n");
out.flush();
} catch (IOException ex) {
ex.printStackTrace();
errorsNum++;
} catch (InterruptedException ex) {
ex.printStackTrace();
errorsNum++;
}finally {
try {
if (in != null)
in.close();
if (out != null)
out.close();
if (connection != null)
connection.close();
} catch (IOException ex) {
}
}
}
}

public static void main(String[] args) {
BlockingServer server = new BlockingServer();
server.start();
}
}
fishyqd 2006-09-15
  • 打赏
  • 举报
回复
用read(byte[])将当前输入流中 b.length 个字节数据读到一个字节数组中。
Socket socket = new Socket(host,port);
InputStream is = socket.getInputStream();
int c = 0;
StringBuffer sb = new StringBuffer();
bytes rec[] = new bytes[];
is.read(bytes);
……//将bytes转为string
System.out.println("receive string is " + sb.toString());
zhucg518 2006-09-15
  • 打赏
  • 举报
回复
建了
我用socket.getOutputStream().write("hello world".getBytes());服务器也收到了
然后服务器返回一串这样的信息
01 5e 09 d5 bc 32 98 79 5c f0 00 0a 50 10 43 cd 7c 08 00 00
我用socket.getInputStream()读不到阿。
iori97king 2006-09-15
  • 打赏
  • 举报
回复
socket.getInputStream();

socket建立了没?

ServerSocket ss=mew ServerSocket(int port) ;
Socket sk=ss.accept();
wmzsl 2006-09-15
  • 打赏
  • 举报
回复
如果真的想改,你把reader和writer改成stream不就好了
wmzsl 2006-09-15
  • 打赏
  • 举报
回复
我写的没问题,你试试
mdxk 2006-09-15
  • 打赏
  • 举报
回复
http://community.csdn.net/Expert/topic/5016/5016983.xml?temp=.6696283
这里下载里面有一个完整的例子
可以自己看看
JM。NET下面就是完整的代码~
polarman 2006-09-15
  • 打赏
  • 举报
回复
向你这样读如果socket不设超时的话肯定会阻塞的
不会返回-1
如果不设超时,服务端和客户端要有个协议,客户端要知道包的长度或包的结束标志,读取到这个长度或结束标志后就得停止
可以简单的这样做

服务端在发送字符串之前,先发送字符长度(int型)

Socket socket = new Socket(host,port);
InputStream is = socket.getInputStream();
int c = 0;
StringBuffer sb = new StringBuffer();
int len = is.read();
int cnt = 0;
while((c = is.read()) != -1) {
sb.append((char)c);
cnt ++;
if(cnt >= len)
break;
}
System.out.println("receive string is " + sb.toString());
TinyJimmy 2006-09-15
  • 打赏
  • 举报
回复
对socket读取数据的方法一般用

while (true) {
byte[] bytes = new byte[Base.BUFFER_SIZE];
int readSize = in.read(bytes);
if (readSize == -1) {
break; //对方关闭socket
}
if (readSize == 0) {
break; //通信等待超时
}
//处理你的请求
String str = new String(bytes, 0, readSize);
...
}
mater789 2006-09-15
  • 打赏
  • 举报
回复
java的socket是利用流连接
如果连接上了,就肯定建立了输入输出流的实例
mater789 2006-09-15
  • 打赏
  • 举报
回复
把你的服务器winsock的代码贴出来
emin_lee 2006-09-15
  • 打赏
  • 举报
回复
mark!
zhucg518 2006-09-15
  • 打赏
  • 举报
回复
程序执行到is.read()就死掉了。下一行的System.out.println(sb.toString())不执行了哦
加载更多回复(2)

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧

手机看
关注公众号

关注公众号

客服 返回
顶部