运行异常如下:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at java.net.Socket.<init>(Socket.java:366)
at java.net.Socket.<init>(Socket.java:180)
at base.socketDemo.main(socketDemo.java:24)
代码如下:public class socketDemo {
/**
* @param args
* @throws IOException
* @throws Exception
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Socket s = null;
try {
s = new Socket("127.0.0.1",10003);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("a.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStream ot = null;
try {
ot = s.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String line = null;
try {
while((line = br.readLine())!=null){
ot.write(line.getBytes());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
s.shutdownOutput();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream is = null;
try {
is = s.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] b = new byte[1024];
int num = 0;
try {
num = is.read(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(new String(b,0,num));
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Server{
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(10003);
Socket s = ss.accept();
System.out.println(s.getInetAddress().getHostAddress());
InputStream is = s.getInputStream();
FileOutputStream fot = new FileOutputStream("bb.txt");
byte[] buf=new byte[1024];
int num = 0;
while((num =is.read(buf))!=-1 ){
fot.write(buf, 0, num);
}
OutputStream ops = s.getOutputStream();
ops.write("上传成功".getBytes());
ss.close();
s.close();
ops.close();
}
}
|