关于socket的编程一般同时也使用线程来实现的,否则极易阻塞。
你的问题是server没得到socket,当然有null pointer了,client就没法连上了。你在server中新建线程,来实现监听client的连接,发现有连接再做处理。给你一个简单的例子吧:import javax.swing.UIManager;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.net.*;public class appServer implements Runnable
{
public static final int Port = 8899;
boolean run_flag=false;
ServerSocket mServerSocket = null;
Thread runner = null; public CMainFrame frame = null;/*当然要用个窗口了*/ /**Construct the application*/
public appServer()
{
}
public void start()
{
try{
if(!run_flag) {
mServerSocket = new ServerSocket(Port);
run_flag=true;
runner = new Thread(this);
runner.start();
}
}
catch(Exception ex){
ex.printStackTrace(System.err);
}
}
public void stop()
{
try{
if(run_flag){
run_flag=false;
runner=null;
mServerSocket.close();
}
}
catch(Exception ex){
//ex.printStackTrace(System.err);
}
}
public void run()
{
while(run_flag)
{
try{
Socket socket = mServerSocket.accept();
/*这里了!!!有一个socket交由一个独立的线程去处理,server继续监听*/
ServerThread one = ServerThread.createServerThread(socket,this); }catch( IOException e ){
// e.printStackTrace();
stop();
}
}
} public void init()
{
frame = new CMainFrame(this);
//Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
} /**Main method*/
public static void main(String[] args) {
try {
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
UIManager.put("MenuItem.font",new Font("宋体",Font.PLAIN,12));
UIManager.put("Menu.font",new Font("宋体",Font.PLAIN,12));
UIManager.put("Button.font",new Font("宋体",Font.PLAIN,12));
UIManager.put("Tree.font",new Font("宋体",Font.PLAIN,12));
UIManager.put("Label.font",new Font("宋体",Font.PLAIN,12));
}
catch(Exception e) {
e.printStackTrace();
}
appServer server = new appServer();
server.init();
}
}
上面的程序不要直接测试,它只是一个部分。关键是你要写一个线程来监听,有socket时交由新的线程来处理。
在客户端倒无所谓了,打开socket,发完请求,取响应,关闭socket。
connection.close();
问题可能出在这里呀!!connection 本来就是空的!!
BufferedInputStream bis=new BufferedInputStream(s.getInputStream());
int c;
while ((c=bis.read())!=-1) System.out.print((char)c);哪位老兄有ftp实现的代码,可以分享一下
然后报告说 decriptor 不是一个socket.
不能write,气死我了
谁能解决这个问题??package proxy;
/*************************************
* 一个基础的代理服务器类
*************************************
*/
import java.net.*;
import java.io.*;public class HPthread extends Thread {
static public int CONNECT_RETRIES=5;
static public int CONNECT_PAUSE=5;
static public int TIMEOUT=50;
static public int BUFSIZ=1024;
static public boolean logging = false;
static public OutputStream log=null;
// 传入数据用的Socket
protected Socket socket;
// 上级代理服务器,可选
static private String parent=null;
static private int parentPort=-1; PipedOutputStream pos;
PipedInputStream pis; PipedOutputStream pos1;
PipedInputStream pis1; InputStream is;
OutputStream os; static public void setParentProxy(String name, int pport) {
parent=name;
parentPort=pport;
} // 在给定Socket上创建一个代理线程。
public HPthread(Socket s) {
socket=s;
String line;
String host;
int port=80;
Socket outbound=null;
try {
socket.setSoTimeout(TIMEOUT);
is=socket.getInputStream();
os=null; try {
// 获取请求行的内容
line="";
host="";
int state=0;
boolean space;
while (true) {
int c=is.read();
if (c==-1) break;
if (logging) writeLog(c,true);
space=Character.isWhitespace((char)c);
switch (state) {
case 0:
if (space) continue;
state=1;
case 1:
if (space) {
state=2;
continue;
}
line=line+(char)c;
break;
case 2:
if (space) continue; // 跳过多个空白字符
state=3;
case 3:
if (space) {
state=4;
// 只取出主机名称部分
String host0=host;
int n;
n=host.indexOf("//");
if (n!=-1) host=host.substring(n+2);
n=host.indexOf('/');
if (n!=-1) host=host.substring(0,n);
// 分析可能存在的端口号
n=host.indexOf(":");
if (n!=-1) {
port=Integer.parseInt(host.substring(n+1));
host=host.substring(0,n);
}
host=processHostName(host0,host,port,socket);
if (parent!=null) {
host=parent;
port=parentPort;
}
int retry=CONNECT_RETRIES;
while (retry--!=0) {
try {
outbound=new Socket(host,port);
break;
} catch (Exception e) { }
// 等待
Thread.sleep(CONNECT_PAUSE);
}
if (outbound==null) break; outbound.setSoTimeout(TIMEOUT);
//pipe(is,outbound.getInputStream(),os,socket.getOutputStream()); pos=new PipedOutputStream();
pis=new PipedInputStream(pos); pos1=new PipedOutputStream();
pis1=new PipedInputStream(pos1);
Consumer co = new Consumer(outbound,pis,pos1,line,host0); this.start();
co.start(); break;
}
host=host+(char)c;
break;
}
}
}
catch (IOException e) { } } catch (Exception e) { }
finally {
try { socket.close();} catch (Exception e1) {}
try { outbound.close();} catch (Exception e2) {}
} } public void writeLog(int c, boolean browser) throws IOException {
log.write(c);
} public void writeLog(byte[] bytes,int offset, int len, boolean browser) throws IOException {
for (int i=0;i<len;i++) writeLog((int)bytes[offset+i],browser);
}
// 默认情况下,日志信息输出到
// 标准输出设备
// 派生类可以覆盖它
public String processHostName(String url, String host, int port, Socket sock) {
java.text.DateFormat cal=java.text.DateFormat.getDateTimeInstance();
//System.out.println(cal.format(new java.util.Date()) + " - " + url + " "
// + sock.getInetAddress()+"\n");
return host;
} // 执行操作的线程
public void run() {
try {
System.out.println("client run");
int ir;
byte bytes[]=new byte[BUFSIZ];
while (true) {
try {
if ((ir=is.read(bytes))>0) {
pos.write(bytes,0,ir);
pos.flush();
sleep(CONNECT_PAUSE); if (logging) writeLog(bytes,0,ir,true);
}
else if (ir<0)
break;
} catch (InterruptedIOException e) { }
try {
if ((ir=pis1.read(bytes))>0) { os.write(bytes,0,ir);
os.flush();
sleep(CONNECT_PAUSE); if (logging) writeLog(bytes,0,ir,false);
}
else if (ir<0)
break;
} catch (InterruptedIOException e) { }
}
} catch (Exception e0) {
e0.printStackTrace(System.out);
System.out.println("Pipe异常: " + e0);
} }
void pipe(InputStream is0, InputStream is1,
OutputStream os0, OutputStream os1) throws IOException {
try {
int ir;
byte bytes[]=new byte[BUFSIZ];
while (true) {
try {
if ((ir=is0.read(bytes))>0) {
os0.write(bytes,0,ir);
if (logging) writeLog(bytes,0,ir,true);
}
else if (ir<0)
break;
} catch (InterruptedIOException e) { }
try {
if ((ir=is1.read(bytes))>0) {
os1.write(bytes,0,ir);
if (logging) writeLog(bytes,0,ir,false);
}
else if (ir<0)
break;
} catch (InterruptedIOException e) { }
}
} catch (Exception e0) {
System.out.println("Pipe异常: " + e0);
}
}
static public void startProxy(int port,Class clobj) {
ServerSocket ssock;
Socket sock;
try {
ssock=new ServerSocket(port);
while (true) {
Class [] sarg = new Class[1];
Object [] arg= new Object[1];
sarg[0]=Socket.class;
try {
java.lang.reflect.Constructor cons = clobj.getDeclaredConstructor(sarg);
arg[0]=ssock.accept();
cons.newInstance(arg); // 创建HPthread或其派生类的实例
} catch (Exception e) {
Socket esock = (Socket)arg[0];
try { esock.close(); } catch (Exception ec) {}
}
}
} catch (IOException e) {e.printStackTrace(System.out);
}
}
// 测试用的简单main方法
static public void main(String args[]) {
System.out.println("在端口9909启动代理服务器\n");
HPthread.log=System.out;
HPthread.logging=true;
HPthread.startProxy(9909,HPthread.class);
}
}
class Consumer extends Thread{
static public int CONNECT_RETRIES=5;
static public int CONNECT_PAUSE=5;
static public int TIMEOUT=50;
static public int BUFSIZ=1024; InputStream is;
OutputStream os;
InputStream is1;
OutputStream os1;
Socket out;
public Consumer(Socket outbound,InputStream ris,OutputStream ros,String line,String host0){ is=ris;
os=ros; out=outbound;
try{
os1=out.getOutputStream();
os1.write(line.getBytes());
os1.write(' ');
os1.write(host0.getBytes());
os1.write(' ');
os1.flush(); is1=out.getInputStream();
//os1=out.getOutputStream();
} catch(Exception e){}
}
public void run(){ try { int ir;
byte bytes[]=new byte[BUFSIZ];
System.out.println("consuming");
while (true) { try { if ((ir=is.read(bytes))>0) { //read from outbound for (int i=0;i<ir;i++) System.out.write((int)bytes[i]);
os1.write(bytes,0,ir); // write to client
os1.flush();
sleep(CONNECT_PAUSE); }
else if (ir<0)
break;
} catch (InterruptedIOException e) { e.printStackTrace(System.out);} try { if ((ir=is1.read(bytes))>0) { //read from outbound for (int i=0;i<ir;i++) System.out.write((int)bytes[i]);
os.write(bytes,0,ir); // write to client
os.flush();
sleep(CONNECT_PAUSE);
}
else if (ir<0)
break;
} catch (InterruptedIOException e) { e.printStackTrace(System.out);} }
} catch (Exception e0) {
e0.printStackTrace(System.out);
System.out.println("Pipe异常: " + e0);
}
}
}