【发布时间】:2014-03-22 15:21:07
【问题描述】:
我有一个服务器套接字和一个客户端套接字。我已经为这两个套接字创建了一个缓冲的输入和输出流。我已经在它们之间建立了连接。现在我已经通过客户端套接字将数据发送到服务器套接字BufferedOutputStream 并已从服务器套接字读取并显示它。当我尝试将数据发送回客户端套接字时,它会抛出异常,说套接字已关闭。 这是代码 服务器应用代码:
import java.io.*;
import java.net.*;
public class MyServer
{
public static void main(String args[]) throws Exception
{
int c;
ServerSocket myServer=new ServerSocket(4341);
Socket cSocket;
cSocket =myServer.accept();
System.out.println("connection made");
InputStream in = cSocket.getInputStream();
OutputStream out = cSocket.getOutputStream();
BufferedInputStream bin = new BufferedInputStream(in);
BufferedOutputStream bout = new BufferedOutputStream(out);
while ((c=bin.read())!=-1)
{
//c=in.read();
System.out.println((char)c);
bout.write(c);
//System.out.print("junaid");
}
System.out.println("connection made");
bout.flush();
cSocket.shutdownOutput();
cSocket.close();
myServer.close();
}
}
客户端应用程序:
import java.io.*;
import java.net.Socket;
public class IOStreams
{
public static void main(String args[]) throws Exception
{
int c;
Socket s = new Socket("localhost",4341);
InputStream in=s.getInputStream();
OutputStream out=s.getOutputStream();
BufferedInputStream bin = new BufferedInputStream(s.getInputStream());
BufferedOutputStream bout = new BufferedOutputStream(s.getOutputStream());
String myStr="what is google";
byte buf[] = myStr.getBytes();
try
{
bout.write(buf);
}
catch(Exception e)
{
System.out.print(e);
}
bout.flush();
//InputStream in = s.getInputStream();
//OutputStream out =s.getOutputStream();
s.shutdownOutput();
while((c=bin.read()) !=-1)
{
//System.out.print("junaid");
System.out.print((char) c);
}
//System.out.println(a);
s.close();
}
}
问题是,当我只从服务器套接字输入流中读取时,它工作正常,但是当我也尝试从客户端套接字的输入流中读取时,它会抛出异常。我知道我已经关闭了客户端套接字的 bufferedOutputStream 但是如果我不关闭它会卡在服务器套接字的 while 循环中。 我的目标是将数据从客户端发送到服务器然后显示并将该数据发送回客户端并再次显示。我已成功将数据从客户端发送到服务器并显示但我无法发送它回到客户端。我的方法有什么问题。我不需要代码来了解如何在不关闭连接的情况下发送和接收数据。
【问题讨论】:
-
我读得很清楚,这不是我要问的亲爱的,请至少阅读我所问的
-
我为此研究了很多,但仍然被降级。太可惜了