本帖最后由 王金科 于 2012-8-24 17:29 编辑
- import java.io.*;
- import java.net.*;
- public class TransTextDemo {
- /**
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- Socket s = new Socket("127.0.0.1",10006);
- ServerSocket ss = new ServerSocket(10006);
-
- new Thread(new TransServer(ss)).start();
- new Thread(new TransClient(s)).start();
- }
- }
- class TransClient implements Runnable{
- private Socket s;
- TransClient(Socket s){
- this.s = s;
- }
- public void run(){
- //定义读取键盘数据的流对象
- BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
-
- try {
- //定义目的,将数据写入到socket输出流,发给服务端
- PrintWriter out = new PrintWriter(s.getOutputStream(),true);
-
- //定义一个socket读取流,读取服务端返回的数据
- BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
-
- String line = null;
- while((line=bufr.readLine())!=null){
- if("over".equals(line)){
- break;
- }
- out.println(line);
- String str = bufIn.readLine();
- System.out.println("server:"+str);
- }
- bufr.close();
- s.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- class TransServer implements Runnable{
- private ServerSocket ss;
- TransServer(ServerSocket ss){
- this.ss = ss;
- }
-
- public void run(){
- try {
- Socket s = ss.accept();
-
- //读取socket流中的数据
- BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
-
- //目的,socket输出流,将大写数据写入到socket输出流,并发送给客户端
-
- PrintWriter out = new PrintWriter(s.getOutputStream(),true);
- String line =null;
- while((line=bufIn.readLine())!=null){
- out.println(line);
- }
- s.close();
- ss.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
复制代码 提示:- Exception in thread "main" java.net.ConnectException: Connection refused: connect
- at java.net.DualStackPlainSocketImpl.connect0(Native Method)
- at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
- at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
- at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
- at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
- at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
- at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
- at java.net.Socket.connect(Socket.java:579)
- at java.net.Socket.connect(Socket.java:528)
- at java.net.Socket.<init>(Socket.java:425)
- at java.net.Socket.<init>(Socket.java:208)
- at cn.study.inet.TransTextDemo.main(TransTextDemo.java:35)
复制代码 |
|