请教一个Socket技术问题.

FindingMyLeader 2014-05-13 02:07:09
高手,我写了一段程序:
是Socket通信的程序.
接收方源代码如下:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.net.Socket;
import java.util.UUID;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;

public class MyServer3 extends JFrame{
private static final long serialVersionUID = -6927612627246594189L;
private static MyJTextPane jtp1;
private MyJTextPane jtp2;
private JButton jb;
String MyFilePath = "";
static int MyLover = 0;

public static void main(String[] args) {
new MyServer3();
}

public void start(){

try {
System.out.println("s" + 1);
SocketServer ss=new SocketServer(9999);
System.out.println("s" + 2);


while(true) {
Socket s=ss.nextSocket();
System.out.println("s" + 3);
String str = ss.read(s);
String[] buffer = str.split("丗");
String MyObjIP = buffer[0];
String MyObjNum = buffer[1];
MyFilePath = "C:\\"+str+"\\"+MyObjNum+"\\aa.jpg";
new ServerTcpListener("C:\\"+str+"\\"+MyObjNum+"\\aa.jpg");
ss.write(s, GetMyUserIP.getMyIP());
final ClipboardUtil.MyImgTextContent mydata=(ClipboardUtil.MyImgTextContent)ss.readObject(s);
ClipboardUtil.MyImgTextContent mylocaldata = new ClipboardUtil.MyImgTextContent();
for(String c : mydata){
if(c.startsWith("text")) {
mylocaldata.content.add(c);
} else {
String filePath = "D:/" + UUID.randomUUID() + ".jpg";
String[] sss = c.replaceAll("img-", "").split(",");
byte[] bs = new byte[sss.length];
for(int i = 0; i < bs.length; i++) {
bs[i] = Byte.parseByte(sss[i]);
}
File f = new File(filePath);
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bs);
fos.flush();
fos.close();
mylocaldata.content.add("img-" + filePath);
}
}
jtp1.setContent(mylocaldata,"");
}
} catch (Exception e) {
e.printStackTrace();
}
}

public MyServer3(){
super("不改原创");
this.setTitle("MyServer3端点");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
this.setLayout(new GridLayout(3, 1));
jtp1 = new MyJTextPane(false);
jtp2 = new MyJTextPane(true);
jtp2.setBorder(BorderFactory.createLineBorder(new Color(0, 0, 0)));
jb = new JButton("send");
jb.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
jtp1.setContent(jtp2.getContent(),"");
jtp2.setText("");
jtp2.grabFocus();
}
});

this.add(new JScrollPane(jtp1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane. HORIZONTAL_SCROLLBAR_NEVER));
this.add(new JScrollPane(jtp2, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane. HORIZONTAL_SCROLLBAR_NEVER));
//----------------------------------
JPanel pan = new JPanel();
JButton btn = new JButton("Get Text");
btn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String content = jtp1.getText();
System.out.println(content);

}
});
pan.add(jb);
pan.add(btn);
this.add(pan);

//----------------------------------

this.setSize(400, 600);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
start();
}

}

发送方的代码为:

import java.awt.Color;

public class MyClient3 extends JFrame{
/**
* 欢迎大家使用这个源码 如有疑问请加qq群:151648295
*
*/
/**
* @param args
*/

private static final long serialVersionUID = -6927612627246594189L;
private MyJTextPane jtp1;
private MyJTextPane jtp2;
private JButton jb;

SocketClient s;
ObjectOutputStream oos;


public MyClient3() {
super("不改原创");
System.out.println(11);
s=new SocketClient("192.168.1.3",9999);
System.out.println(1);
this.setLayout(new GridLayout(3, 1));
jtp1 = new MyJTextPane(false);
jtp2 = new MyJTextPane(true);
jtp2.setBorder(BorderFactory.createLineBorder(new Color(0, 0, 0)));
jb = new JButton("send");
jb.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
jtp1.setContent(jtp2.getContent(),"");
ClipboardUtil.MyImgTextContent mydata = jtp2.getContent();
s.writeStr(GetMyUserIP.getMyIP()+"丗001", "MyClient3");
new ClientTcpSend("E:\\aa.jpg","127.0.0.1");
MyClient3method(mydata);
jtp2.setText("");
jtp2.grabFocus();
}
});

this.add(new JScrollPane(jtp1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane. HORIZONTAL_SCROLLBAR_NEVER));
this.add(new JScrollPane(jtp2, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane. HORIZONTAL_SCROLLBAR_NEVER));
this.add(jb);

this.setSize(400, 600);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
// TODO Auto-generated method stub
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub

new MyClient3();
}
}).start();
}

public void MyClient3method(ClipboardUtil.MyImgTextContent mydata){
try {
ClipboardUtil.MyImgTextContent t = new ClipboardUtil.MyImgTextContent();
for(String s : mydata) {
if(s.startsWith("text")) {
t.content.add(s);
} else {
File f = new File(s.replaceFirst("img-", ""));
byte[] bs = new byte[(int)f.length()];
FileInputStream fis = new FileInputStream(f);
fis.read(bs);
StringBuilder sb = new StringBuilder();
for(byte b : bs) {
sb.append(b + ",");
}
t.content.add("img-" + sb.toString());
fis.close();
}
}
s.readStr();
s.writeObj(t);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

请求高手点拨:
我的运行结果:
接收端监视器现场为:

发送端监视器现场为:

上述代码中的Socket API的源代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class SocketServer {
private ServerSocket ss = null;
private Map<Socket, BufferedReader> rm = new HashMap<Socket, BufferedReader>();
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
BufferedReader br = null;
PrintWriter pw = null;

public SocketServer(int port) {
try {
ss = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}

public Socket nextSocket() {
Socket s = null;
try {
s = ss.accept();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}

public String read(Socket s) throws IOException {
if (null == (br = rm.get(s))) {
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
rm.put(s, br);
}
return br.readLine();
}

public Object readObject(Socket s){
Object obj = null;
try {
ois = new ObjectInputStream(s.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
obj = ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj;
}

public void writeObject(Socket s,Object obj){
try {
oos = new ObjectOutputStream(s.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos.writeObject(obj);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void write(Socket s, String content) throws IOException {
pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
pw.println(content);
pw.flush();
}

public void getMyResourceBack(){
if(pw!=null){
pw.close();
}
if(br!=null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(rm!=null){
rm.clear();
}if(ss!=null){
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

之后的API的下一个类型:“SocketClient”,小弟将贴在下一张帖子中。
希望高手能够帮忙.
...全文
255 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Finding_ChenHaoNan 2014-05-14
  • 打赏
  • 举报
回复
是尚硅谷的李毅老师吗?!!!!!
哎呀妈呀!!!!!别跑了!!!!!!

谢谢李毅老师的点拨!!
我的错误已经解决!!
原因在这里:

这里,ObjectInputStream类的实例在进行new创建的时候,需要远程的发起方传过来一个Socket对象,从而对这个远程的Socket进行流的读取.
所以,在进行调试的时候,代码走到
s=new SocketClient("192.168.1.3",9999);
这里的时候,出现了:
停住.
的问题.
而在接收端,我的代码有这里的处理机制:

所以导致了“死锁”的“双向等待”的问题出现.
谢谢组织李毅大帝的相助!!!!!!
有李毅!!!!无懦夫!!!!
java_liyi 2014-05-13
  • 打赏
  • 举报
回复
懒得看代码了 就发个链接你看看吧,我估计是一个问题 http://zhidao.baidu.com/link?url=rGfagL0ehpJG1gqlLqbzdHjIeZuBRa_HLCZ0nmracilAvXclKX2qSQxObGTGuzAUWVoZCyiXpFt6SmEza2m4eq
FindingMyLeader 2014-05-13
  • 打赏
  • 举报
回复
其中的9999通信端口是通的. 小弟已经检查过了.
FindingMyLeader 2014-05-13
  • 打赏
  • 举报
回复
上述帖子中Socket API的“SocketClient类型”源代码如下:

 
import java.io.BufferedInputStream;
 
public class SocketClient {
 
    public Socket getS() {
        return s;
    }
 
    public void setS(Socket s) {
        this.s = s;
    }
 
    private Socket s;
    private InputStream in;
    private OutputStream out;
    private BufferedInputStream inByte;
    private OutputStream outByte;
    private BufferedReader inStr;
    private PrintWriter outStr;
    public ObjectOutputStream oos = null;
    public ObjectInputStream ois = null;
     
    private long size = 0;
 
    public SocketClient(String ip, int port) {
        try {
            s = new Socket(ip, port);
 
            in = s.getInputStream();
            out = s.getOutputStream();
            
            inByte = new BufferedInputStream(in);
            outByte = out;
            oos = new ObjectOutputStream(out);
            ois = new ObjectInputStream(in);
            inStr = new BufferedReader(new InputStreamReader(in));
            outStr = new PrintWriter(new OutputStreamWriter(out));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public Object readObj(){
    	ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(in);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
    	Object obj = null;
    	try {
			obj = ois.readObject();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
    }
    
    public void writeObj(Object obj){
    	try {
    		ObjectOutputStream oos = new ObjectOutputStream(out);
			oos.writeObject(obj);
			oos.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
 
    public String readStr() throws IOException {
        synchronized (this.in) {
            return this.inStr.readLine();
        }
    }
 
    public void writeStr(String content,String MyThreadname) {
        synchronized (this.out) {
        	String IP = GetMyUserIP.getMyIP();
            outStr.println(content+"丗"+IP+"丗"+MyThreadname);
            outStr.flush();
        }
    }
 
    public File readToFile(File file) throws IOException {
        synchronized (this.in) {
            FileOutputStream fos = new FileOutputStream(file);
            byte[] temp = new byte[1024 * 8];
            int count = 0;
            while (-1 != (count = this.inByte.read(temp))) {
                fos.write(temp, 0, count);
                fos.flush();
            }
            fos.close();
            return file;
        }
    }
 
    public void writeFile(File file) {
        synchronized (this.out) {
            size = file.length();
            this.noticeFileSize(size);
 
            FileInputStream fis;
            try {
                fis = new FileInputStream(file);
                byte[] temp = new byte[1024 * 8];
                int count = 0;
                while (-1 != (count = fis.read(temp))) {
                    this.outByte.write(temp, 0, count);
                    this.outByte.flush();
                }
                fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
 
//            long progress = 0;
//            while (size != (progress = getServerReceiveSize())) {
//                //////"progress : " + (progress / (size / 100)) + "%");
//            }
        }
    }
 
    private void noticeFileSize(long l) {
        String str = l + "";
        int j = 19 - str.length();
        for (int i = 0; i < j; i++) {
            str = "0" + str;
        }
        this.writeByByte(str);
    }
 
    protected void writeByByte(String content) {
        synchronized (this.out) {
            try {
                this.out.write(content.getBytes());
                this.out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    private long getServerReceiveSize() {
        synchronized (in) {
            byte[] b = new byte[19];
            try {
                this.in.read(b);
            } catch (IOException e) {
                e.printStackTrace();
            }
 
            return Long.parseLong(new String(b));
        }
    }
     
    public String getProgress() {
        long l = this.getServerReceiveSize() / (size / 100);
        if(100 == l) {
            return null;
        }
        return l + " %";
    }
     
    public void getMyResourceBack(){
    	if(inStr!=null){
            try {
                inStr.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }if(outStr!=null){
            outStr.close();
        }
        if(s!=null){
            try {
                s.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }if(in!=null){
            try {
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }if(out!=null){
            try {
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
 
}
希望能够得到组织CSDN与路过的高手的点拨: 小弟的代码,为什么会有: 接收端能够运行出界面,但是发起端无法运行出界面,在进行debug调试的时候,会在第1张帖子中的MyClient3类型中的第“24行”代码的位置停止了. 之后小弟又对接收端进行了调试,停在这个位置: MyServer3这个类型中的第39行的:
String str = ss.read(s);
这个位置. 希望高手能够点拨: 为什么小弟的接收端停在具有阻塞功能的“read()”方法后,小弟的发起端也会停住? 就停在这句建立连接的代码行上: s=new SocketClient("192.168.1.3",9999); 希望高手能够为小弟做一下分析: 小弟的代码现场的问题,出在什么位置? 小弟在线等.
vnvlyp 2014-05-13
  • 打赏
  • 举报
回复
代码贴了这么长,我都不知道你有什么问题。。

62,634

社区成员

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

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