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){ ClipboardUtil.MyImgTextContent t = new ClipboardUtil.MyImgTextContent(); for(String s : mydata) { if(s.startsWith("text")) { t.content.add(s); } else { t.content.add(s); } } s.writeObj(t); } } public class ClientTcpSend {
public static String clientip = "127.0.0.1"; public static int port = 3456;
public ClientTcpSend(String Localfilepath,String MyFriIP){ clientip = MyFriIP; int length = 0; byte[] sendBytes = null; Socket socket = null; DataOutputStream dos = null; FileInputStream fis = null; try { try { socket = new Socket(clientip, port); dos = new DataOutputStream(socket.getOutputStream()); File file = new File(Localfilepath); fis = new FileInputStream(file); sendBytes = new byte[1024*4]; while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) { dos.write(sendBytes, 0, length); dos.flush(); } } finally { if (dos != null) dos.close(); if (fis != null) fis.close(); if (socket != null) socket.close(); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { int length = 0; byte[] sendBytes = null; Socket socket = null; DataOutputStream dos = null; FileInputStream fis = null; try { try { socket = new Socket(); socket.connect(new InetSocketAddress(clientip, port),30 * 1000); dos = new DataOutputStream(socket.getOutputStream()); File file = new File("F:\\aa.jpg"); fis = new FileInputStream(file); sendBytes = new byte[1024*4]; while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) { dos.write(sendBytes, 0, length); dos.flush(); } } finally { if (dos != null) dos.close(); if (fis != null) fis.close(); if (socket != null) socket.close(); } } catch (Exception e) { e.printStackTrace(); } } }
public class GetMyUserIP {
public static String getMyIP(){
String Objip = "";
try {
Objip = java.net.InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Objip;
}
}
public class MyImgComponent extends JLabel {
private boolean isView = false;
private long lastTime = -1;
public static final int h;
public static final int w;
static {
Insets scrInsets = Toolkit.getDefaultToolkit().getScreenInsets(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration());
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
h = scrSize.height - scrInsets.bottom - scrInsets.top;
w = scrSize.width - scrInsets.left - scrInsets.right;
} private String imgPath; public MyImgComponent(Icon icon) {
this.setIcon(icon);
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if(new Date().getTime() - lastTime > 800) {
lastTime = new Date().getTime();
return;
} else {
lastTime = -1;
}
if(isView) {
return;
}
isView = true;
final JWindow jf = new JWindow();
final JWindow jf2 = new JWindow();
JLabel jl = new JLabel();
try {
Icon i = new ImageIcon(new URL("file:///" + imgPath));
jl.setSize(i.getIconWidth(), i.getIconHeight());
jl.setIcon(i);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
JPanel jp2 = new JPanel();
jp2.setSize(jl.getWidth() + 300, jl.getHeight() + 300);
jp2.setBackground(Color.black);
jf.add(jl);
jf2.add(jp2);
jf.setSize(jl.getWidth(), jl.getHeight());
jf2.setSize(jp2.getWidth(), jp2.getHeight());
jf.setLocation((MyImgComponent.w - jl.getWidth()) / 2, (MyImgComponent.h - jl.getHeight()) / 2);
jf2.setLocation((MyImgComponent.w - jp2.getWidth()) / 2, (MyImgComponent.h - jp2.getHeight()) / 2);
AWTUtilities.setWindowOpacity(jf2, 0.8f);
JFrame.setDefaultLookAndFeelDecorated(true);
AWTUtilities.setWindowShape(jf2, new RoundRectangle2D.Double(0.0D, 0.0D, jf2.getWidth(), jf2.getHeight(), 20.0D, 20.0D));
jf.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
jf.dispose();
jf2.dispose();
isView = false;
}
});
jf2.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
jf.dispose();
jf2.dispose();
isView = false;
}
});
jf2.setVisible(true);
jf.setVisible(true);
} });
} public void setIcon(Icon icon) {
if (null != icon) {
imgPath = icon.toString().replaceFirst("file:/", "");
}
super.setIcon(icon);
}}接收端源代码:(入口类)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;
static HashMap<Integer,String> mypicpath = new HashMap<Integer,String>();
static Integer mypicnum = 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();//把服务端页DEbug一下好的,大哥.
System.out.println("s" + 3);
String str = "";
try{
str = ss.read(s);
}catch(Exception e){
str = "127.0.0.1丗001丗127.0.0.1丗MyServerHost";
}
String[] buffer = str.split("丗");
String judgeMyUserInfo = buffer[0];
String MyObjNum = buffer[1];
MyFilePath = "C:\\"+"MyUserChatInfo"+"\\"+MyObjNum+"\\";
int mypicindex = mypicnum++;
new ServerTcpListener(MyFilePath,mypicindex);
System.out.println("di53");
ss.write(s,GetMyUserIP.getMyIP()+"\r\n");
final ClipboardUtil.MyImgTextContent mydata=(ClipboardUtil.MyImgTextContent)ss.readObject(s);
ClipboardUtil.MyImgTextContent mylocaldata = new ClipboardUtil.MyImgTextContent();
System.out.println("di60");
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();}
}
public class ServerTcpListener implements Runnable {
String LocalMyfilesavePath = "C:\\a1.jpg";
static int Mypicnum = 0;
static ArrayList<String> mypicPathbox = new ArrayList<String>();
public static void main(String[] args){
new ServerTcpListener("C:\\aa.jpg",0);
} public ServerTcpListener(String MyfilesavePath,int picnum) {
LocalMyfilesavePath = MyfilesavePath;
try {
final ServerSocket server = new ServerSocket(3456);
Thread th = new Thread(new Runnable() {
public void run() {
try {
System.out.println("开始监听...");
Socket socket = server.accept();
System.out.println("有链接");
receiveFile(socket);
} catch (Exception e) {
}
} }); th.run(); //启动线程运行
} catch (Exception e) {
e.printStackTrace();
}
} public void run() {
}
public void receiveFile(Socket socket) {
String mypicname = "aa"+GetTheSysData.getTheLocalData()+Mypicnum+++".jpg";
byte[] inputByte = null;
int length = 0;
DataInputStream dis = null;
FileOutputStream fos = null;
try {
try {
new CreatOurFolders(LocalMyfilesavePath);
MyServer3.mypicpath.put(Mypicnum,LocalMyfilesavePath);
dis = new DataInputStream(socket.getInputStream());
String mypicpath = LocalMyfilesavePath+File.separator+mypicname;
mypicPathbox.add(mypicpath);
fos = new FileOutputStream(new File(LocalMyfilesavePath+File.separator+mypicname));
inputByte = new byte[1024*4];
System.out.println("开始接收数据...");
while ((length = dis.read(inputByte, 0, inputByte.length)) > 0) {
fos.write(inputByte, 0, length);
fos.flush();
}
System.out.println("完成接收");
} finally {
if (fos != null)
fos.close();
if (dis != null)
dis.close();
if (socket != null)
socket.close();
}
} catch (Exception e) { } }
}
import java.util.Calendar;
public class GetTheSysData {
static String year,month,day=null;
static String datatime = null;
public static String getTheLocalData(){
Calendar now = Calendar.getInstance();
year = String.valueOf(now.get(Calendar.YEAR));
month = String.valueOf(now.get(Calendar.MONTH) + 1);
day = String.valueOf(now.get(Calendar.DAY_OF_MONTH));
if(month.length()==1){
month = "0" + month;
}
if(day.length()==1){
day = "0" + day;
}
return datatime = year+month+day;
}
public static void main(String[] args){
System.out.println(getTheLocalData());
}
}
class CreatOurFolders{
public CreatOurFolders(String path){
String filePath = path;
File fp = new File(filePath);
// 创建目录
if (!fp.exists()) {
fp.mkdirs();
}
}
}
请高手允许我把之后的代码,补发到下面的帖子中.
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(),"UTF-8"));
rm.put(s, br);
}
String s0 = br.readLine();
System.out.println("br.readLine()===="+s0);
return s0;
}
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();
}
}
}
}
发送端的入口类: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();
System.out.println("=========="+GetMyUserIP.getMyIP());
s.writeStr(GetMyUserIP.getMyIP()+"丗001", "MyClient3\r\n");
int len = ClipboardUtil.ps.size();
int len0 = ClipboardUtil.ps.size();
/*String str = */ClipboardUtil.getMyImgTextContentFromClipboard().content.size();//这是消息的长度
//遍历消息
for (String content : ClipboardUtil.getMyImgTextContentFromClipboard()) {
if (null == content) {
continue;
}else if(content.startsWith("img-")){
content = content.replaceFirst("img-", "");
new ClientTcpSend(content,"192.168.1.3");
}
}
// String myfilepath =ClipboardUtil.ps.get(len-1).myuserpicpath.;
System.out.println("di52");
try {
s.readStr();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("di58");
MyClient3method(mydata);
jtp2.setText("");
// jtp1.setContent(mydata, MyFilePath);
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){
ClipboardUtil.MyImgTextContent t = new ClipboardUtil.MyImgTextContent();
for(String s : mydata) {
if(s.startsWith("text")) {
t.content.add(s);
} else {
t.content.add(s);
}
}
s.writeObj(t);
}
}
public class ClientTcpSend {
public static String clientip = "127.0.0.1";
public static int port = 3456;
public ClientTcpSend(String Localfilepath,String MyFriIP){
clientip = MyFriIP;
int length = 0;
byte[] sendBytes = null;
Socket socket = null;
DataOutputStream dos = null;
FileInputStream fis = null;
try {
try {
socket = new Socket(clientip, port);
dos = new DataOutputStream(socket.getOutputStream());
File file = new File(Localfilepath);
fis = new FileInputStream(file);
sendBytes = new byte[1024*4];
while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
dos.write(sendBytes, 0, length);
dos.flush();
}
} finally {
if (dos != null)
dos.close();
if (fis != null)
fis.close();
if (socket != null)
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) {
int length = 0;
byte[] sendBytes = null;
Socket socket = null;
DataOutputStream dos = null;
FileInputStream fis = null;
try {
try {
socket = new Socket();
socket.connect(new InetSocketAddress(clientip, port),30 * 1000);
dos = new DataOutputStream(socket.getOutputStream());
File file = new File("F:\\aa.jpg");
fis = new FileInputStream(file);
sendBytes = new byte[1024*4];
while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
dos.write(sendBytes, 0, length);
dos.flush();
}
} finally {
if (dos != null)
dos.close();
if (fis != null)
fis.close();
if (socket != null)
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
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;
inStr = new BufferedReader(new InputStreamReader(in,"UTF-8"));
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.write(content+"丗"+IP+"丗"+MyThreadname);
System.out.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.flush();
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();
}
}
}
}希望得到高手点拨,为什么我的两个端点,在接收端运行主类之后,再运行发送端,会有:
在我把C端的程序运行窗口的留言板中输入了“CJCO”四个字后,会有如下的现场出现: 我在点击了“发送”按钮之后,会有“不是施瓦辛格点击的”,“但是..按钮被按下去上不来了”的问题出现?
第二个问题是:
为什么我在下面的C端运行结果贴入了一张图片后,会有:
在我点击了“发送按钮之后”,出现界面:
我的开发环境的后台报出错误为:
(接收端的console窗口的提示为:)
(发送端的console窗口的提示为:)
希望高手能够帮忙:
小弟的这个程序,问题出在哪里,如何修改?
小弟从昨天早晨干到现在了.
小弟休息去了.
希望小弟能够得到组织的帮助,路过高手的不吝赐教与点拨.
让小弟这个天天,不到凌晨6点不睡觉的Java“小轴”,能够,成·为·正·果.
一般socket程序的问题都可以用 控制台来解决和解释, 用swing ui干什么....
system.out, input.readLine(); 等输入输出控制的单纯j2se程序能演示你这个swing所能演示的所有东西.socket写懂了, 那点swing细节还算什么呢....
---------------------------------------------------------------
第1个问题:但是..按钮被按下去上不来了”的问题出现?
因为按下去之后会碰到socket-read阻塞. 如果你用异步去写就没这个问题了. socket 读到的数据放一个静态变量里, swing的ui不停的去扫描这个变量看看读了些什么东西 诸如此类的.第二个问题是: 为什么我在下面的C端运行结果贴入了一张图片后,会有:NumberformateException......
是在没工夫看你那一堆代码啊. 但是这是个简单的: 数据转换错误. 原因是因为你把一个非int/short/byte 的数据进行了强行转换int的操作. 老兄, 先解决低级问题好么.最后建议:
你这个问题关闭吧. 先自己找一个最简单的socket client+server demo学一学再说吧. 然后再想办法把socket代码嵌入到 swing等界面里.