利用Java编写一个程序利用Socket,实现网络的点对点文件传输并且能实现聊天,发个给我学习下 , 好吗?这个时比较简单java聊天传输文件代码的 。
package QQ;
import java.net.*;
import java.io.*;
import java.sql.*;
import java.util.*;
public class QQServer {
public static void main(String args[]) {
try {
HashMapString , Socket hm = new
HashMapString , Socket() ;
// 服务器到8000端口监听(1)
ServerSocket ss = new ServerSocket
(8000);
while (true) {
System.out.println("服务器正在
8000端口监听.....");
Socket s = ss.accept();
MyService t = new MyService();
t.setSocket(s) ;
t.setHashMap(hm) ;
t.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MyService extends Thread {
private Socket s ;
private HashMapString , Socket hm ;
public void setHashMap(HashMapString , Socket hm){
this.hm = hm ;
}
public void setSocket(Socket s){
this.s = s ;
}
public void run() {
try {
// 接收客户端发送来的用户名和密码(2)
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader
(is);
BufferedReader br = new BufferedReader(isr);
String uandp = br.readLine();
// 拆分用户名和密码(4)
String u = "";
String p = "";
try{
u = uandp.split("%")[0];
p = uandp.split("%")[1];
}catch(Exception e){}
// 到数据库中验证(5)
Class.forName
("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection cn = DriverManager
.getConnection(
"jdbc:microsoft:sqlserver://127.0.0.1:1433;databasename=qq2",
"sa", "123");
PreparedStatement ps = cn
.prepareStatement("select
username from username where username=? and password=?");
ps.setString(1, u);
ps.setString(2, p);
ResultSet rs = ps.executeQuery();
// 发送确认信息到客户端(7)
OutputStream os = s.getOutputStream();
OutputStreamWriter osw = new
OutputStreamWriter(os);
PrintWriter pw = new PrintWriter(osw, true);
if (rs.next()) {
pw.println("ok");
//将自己的名字发送给HashMap中的其java聊天传输文件代码他人
(13)
for(Socket ts : hm.values()){
OutputStream tos =
ts.getOutputStream() ;
OutputStreamWriter tosw = new
OutputStreamWriter(tos) ;
PrintWriter tpw = new
PrintWriter(tosw , true) ;
tpw.println("user%" u) ;
}
//将其java聊天传输文件代码他人的名字发送给自己(13)
for(String tu : hm.keySet()){
pw.println("user%" tu) ;
}
//将用户名和对应的Socket存入HashMap
(13)
hm.put(u, s) ;
// 接收客户端发送来的信息(11)
while (true) {
String message = br.readLine
();
if(message.equals("exit")){
for(Socket ts :
hm.values()){
OutputStream
tos = ts.getOutputStream() ;
OutputStreamWriter tosw = new OutputStreamWriter(tos) ;
PrintWriter
tpw = new PrintWriter(tosw , true) ;
tpw.println
("exit%" u);
}
hm.remove(u);
}
String to = message.split
("%")[0];
String mess = message.split
("%")[1];
Socket ts = hm.get(to);
OutputStream tos =
ts.getOutputStream();
【java聊天传输文件代码 java socket 传输文件】OutputStreamWriter tosw = new
OutputStreamWriter(tos);
PrintWriter tpw = new
PrintWriter(tosw, true);
tpw.println("mess%" mess
"\n");
System.out.println(message);
}
} else {
pw.println("err");
}
} catch (Exception e) {}
}
}
急求JavaC/S聊天室代码,有界面,可发消息传文件 , 非常感谢客户端:importjava.awt.BorderLayout;importjava.awt.Color;importjava.awt.GridLayout;importjava.awt.Toolkit;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.Socket;importjava.util.HashMap;importjava.util.Map;importjava.util.StringTokenizer;importjavax.swing.DefaultListModel;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JList;importjavax.swing.JOptionPane;importjavax.swing.JPanel;importjavax.swing.JScrollPane;importjavax.swing.JSplitPane;importjavax.swing.JTextArea;importjavax.swing.JTextField;importjavax.swing.border.TitledBorder;publicclassClient{privateJFrameframe;privateJListuserList;privateJTextAreatextArea;privateJTextFieldtextField;privateJTextFieldtxt_port;privateJTextFieldtxt_hostIp;privateJTextFieldtxt_name;privateJButtonbtn_start;privateJButtonbtn_stop;privateJButtonbtn_send;privateJPanelnorthPanel;privateJPanelsouthPanel;privateJScrollPanerightScroll;privateJScrollPaneleftScroll;privateJSplitPanecenterSplit;privateDefaultListModellistModel;privatebooleanisConnected=false;privateSocketsocket;privatePrintWriterwriter;privateBufferedReaderreader;privateMessageThreadmessageThread;//负责接收消息java聊天传输文件代码的线程privateMaponLineUsers=newHashMap();//所有在线用户//主方法,程序入口publicstaticvoidmain(String[]args){newClient();}//执行发送publicvoidsend(){if(!isConnected){JOptionPane.showMessageDialog(frame,"还没有连接服务器java聊天传输文件代码,无法发送消息!","错误",JOptionPane.ERROR_MESSAGE);return;}Stringmessage=textField.getText().trim();if(message==null||message.equals("")){JOptionPane.showMessageDialog(frame,"消息不能为空!","错误",JOptionPane.ERROR_MESSAGE);return;}sendMessage(frame.getTitle() "@" "ALL" "@" message);textField.setText(null);}//构造方法publicClient(){textArea=newJTextArea();textArea.setEditable(false);textArea.setForeground(Color.blue);textField=newJTextField();txt_port=newJTextField("719");txt_hostIp=newJTextField("127.0.0.1");txt_name=newJTextField("Lei");btn_start=newJButton("连接");btn_stop=newJButton("断开");btn_send=newJButton("发送");listModel=newDefaultListModel();userList=newJList(listModel);northPanel=newJPanel();northPanel.setLayout(newGridLayout(1,7));northPanel.add(newJLabel("端口"));northPanel.add(txt_port);northPanel.add(newJLabel("服务器IP"));northPanel.add(txt_hostIp);northPanel.add(newJLabel("姓名"));northPanel.add(txt_name);northPanel.add(btn_start);northPanel.add(btn_stop);northPanel.setBorder(newTitledBorder("连接信息"));rightScroll=newJScrollPane(textArea);rightScroll.setBorder(newTitledBorder("消息显示区"));leftScroll=newJScrollPane(userList);leftScroll.setBorder(newTitledBorder("在线用户"));southPanel=newJPanel(newBorderLayout());southPanel.add(textField,"Center");southPanel.add(btn_send,"East");southPanel.setBorder(newTitledBorder("写消息"));centerSplit=newJSplitPane(JSplitPane.HORIZONTAL_SPLIT,leftScroll,rightScroll);centerSplit.setDividerLocation(100);frame=newJFrame("客户机");//更改JFramejava聊天传输文件代码的图标://frame.setIconImage(Toolkit.getDefaultToolkit().createImage(Client.class.getResource("qq.png")));frame.setLayout(newBorderLayout());frame.add(northPanel,"North");frame.add(centerSplit,"Center");frame.add(southPanel,"South");frame.setSize(600,400);intscreen_width=Toolkit.getDefaultToolkit().getScreenSize().width;intscreen_height=Toolkit.getDefaultToolkit().getScreenSize().height;frame.setLocation((screen_width-frame.getWidth())/2,(screen_height-frame.getHeight())/2);frame.setVisible(true);//写消息的文本框中按回车键时事件textField.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEventarg0){send();}});//单击发送按钮时事件btn_send.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){send();}});//单击连接按钮时事件btn_start.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){intport;if(isConnected){JOptionPane.showMessageDialog(frame,"已处于连接上状态java聊天传输文件代码,不要重复连接!","错误",JOptionPane.ERROR_MESSAGE);return;}try{try{port=Integer.parseInt(txt_port.getText().trim());}catch(NumberFormatExceptione2){thrownewException("端口号不符合要求!端口为整数!");}StringhostIp=txt_hostIp.getText().trim();Stringname=txt_name.getText().trim();if(name.equals("")||hostIp.equals("")){thrownewException("姓名、服务器IP不能为空!");}booleanflag=connectServer(port,hostIp,name);if(flag==false){thrownewException("与服务器连接失败!");}frame.setTitle(name);JOptionPane.showMessageDialog(frame,"成功连接!");}catch(Exceptionexc){JOptionPane.showMessageDialog(frame,exc.getMessage(),"错误",JOptionPane.ERROR_MESSAGE);}}});//单击断开按钮时事件btn_stop.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){if(!isConnected){JOptionPane.showMessageDialog(frame,"已处于断开状态,不要重复断开!","错误",JOptionPane.ERROR_MESSAGE);return;}try{booleanflag=closeConnection();//断开连接if(flag==false){thrownewException("断开连接发生异常!");}JOptionPane.showMessageDialog(frame,"成功断开!");}catch(Exceptionexc){JOptionPane.showMessageDialog(frame,exc.getMessage(),"错误",JOptionPane.ERROR_MESSAGE);}}});//关闭窗口时事件frame.addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){if(isConnected){closeConnection();//关闭连接}System.exit(0);//退出程序}});}/***连接服务器**@paramport*@paramhostIp*@paramname*/publicbooleanconnectServer(intport,StringhostIp,Stringname){//连接服务器try{socket=newSocket(hostIp,port);//根据端口号和服务器ip建立连接writer=newPrintWriter(socket.getOutputStream());reader=newBufferedReader(newInputStreamReader(socket.getInputStream()));//发送客户端用户基本信息(用户名和ip地址)sendMessage(name "@" socket.getLocalAddress().toString());//开启接收消息的线程messageThread=newMessageThread(reader,textArea);messageThread.start();isConnected=true;//已经连接上了returntrue;}catch(Exceptione){textArea.append("与端口号为:" port "IP地址为:" hostIp "的服务器连接失败!" "\r\n");isConnected=false;//未连接上returnfalse;}}/***发送消息**@parammessage*/publicvoidsendMessage(Stringmessage){writer.println(message);writer.flush();}/***客户端主动关闭连接*/@SuppressWarnings("deprecation")publicsynchronizedbooleancloseConnection(){try{sendMessage("CLOSE");//发送断开连接命令给服务器messageThread.stop();//停止接受消息线程//释放资源if(reader!=null){reader.close();}if(writer!=null){writer.close();}if(socket!=null){socket.close();}isConnected=false;returntrue;}catch(IOExceptione1){e1.printStackTrace();isConnected=true;returnfalse;}}//不断接收消息的线程classMessageThreadextendsThread{privateBufferedReaderreader;privateJTextAreatextArea;//接收消息线程的构造方法publicMessageThread(BufferedReaderreader,JTextAreatextArea){this.reader=reader;this.textArea=textArea;}//被动的关闭连接publicsynchronizedvoidcloseCon()throwsException{//清空用户列表listModel.removeAllElements();//被动的关闭连接释放资源if(reader!=null){reader.close();}if(writer!=null){writer.close();}if(socket!=null){socket.close();}isConnected=false;//修改状态为断开}publicvoidrun(){Stringmessage="";while(true){try{message=reader.readLine();StringTokenizerstringTokenizer=newStringTokenizer(message,"/@");Stringcommand=stringTokenizer.nextToken();//命令if(command.equals("CLOSE"))//服务器已关闭命令{textArea.append("服务器已关闭!\r\n");closeCon();//被动的关闭连接return;//结束线程}elseif(command.equals("ADD")){//有用户上线更新在线列表Stringusername="";StringuserIp="";if((username=stringTokenizer.nextToken())!=null(userIp=stringTokenizer.nextToken())!=null){Useruser=newUser(username,userIp);onLineUsers.put(username,user);listModel.addElement(username);}}elseif(command.equals("DELETE")){//有用户下线更新在线列表Stringusername=stringTokenizer.nextToken();Useruser=(User)onLineUsers.get(username);onLineUsers.remove(user);listModel.removeElement(username);}elseif(command.equals("USERLIST")){//加载在线用户列表intsize=Integer.parseInt(stringTokenizer.nextToken());Stringusername=null;StringuserIp=null;for(inti=0;i
我正在做一个java 聊天程序,要实现传输文件功能,求大神指导~~~最好有示例代码 。。如果是HTTP协议和FTP协议java聊天传输文件代码的java聊天传输文件代码,java版本java聊天传输文件代码的见代码
InputStream ios=new URL("文件bom.zip所在java聊天传输文件代码的WEB目录/bom.zip").openConnection().getInputStream();
BufferedOutputStream bout=new BufferedOutputStream(new FileOutputStream("c:/存放目录/bom.zip"));
byte buff[]=new byte[1024];
int count;
while((count=ios.read(buff))0){
bout.write(buff, 0, count);
}
ios.close();
bout.close();
JAVA 传输文件//以前写java聊天传输文件代码的一个文件传输的小程序,有客户端和服务器端两部分,服务器可//以一直运行 , 客户端传输完一个后退出,当然java聊天传输文件代码你也可以根据你的需要改 。
//服务器端可以支持多个客户端同时上传 , 用到java聊天传输文件代码了多线程
/**
*文件传输,客户端
*@aurth anyx
*/
//package per.anyx.ftp;
import java.net.*;
import java.io.*;
public class FtpClient{
public static void main(String[] args){
if(args.length != 3){
System.out.println("Usage: FtpClient host_add host_port src_file");
System.exit(0);
}
File file = new File(args[2]);
if(!file.exists() || !file.isFile()){
System.out.println("File \""args[2]"\" does not exist or is not a normal file.");
System.exit(0);
}
Socket s = null;
FileInputStream in = null;
OutputStream out = null;
try{
s = new Socket(args[0], Integer.parseInt(args[1]));
in = new FileInputStream(file);
out = s.getOutputStream();
byte[] buffer = new byte[1024*8];
int len = -1;
System.out.println("File tansfer statr...");
while((len=in.read(buffer)) != -1){
out.write(buffer, 0, len);
}
System.out.println("File tansfer complete...");
}catch(Exception e){
System.out.println("Error: "e.getMessage());
System.exit(1);
}finally{
try{
if(in != null) in.close();
if(out != null) out.close();
if(s != null) s.close();
}catch(Exception e){}
}
}
}
/**
*文件传输 , 服务器端
*@aurth anyx
*/
//package per.anyx.ftp;
import java.net.*;
import java.io.*;
public class FtpServer{
public static void main(String[] args){
if(args.length != 1){
System.out.println("Usage: FtpServer server_port");
System.exit(0);
}
ServerSocket ss = null;
try{
ss = new ServerSocket(Integer.parseInt(args[0]));
System.out.println("FtpServer start on port ..."args[0]);
while(true){
Socket s = ss.accept();
new FtpThread(s).start();
System.out.println(s.getInetAddress().getHostAddress()" connected.");
}
}catch(Exception e){
System.out.println("Error: "e.getMessage());
}finally{
try{
if(ss != null) ss.close();
}catch(Exception e){}
}
}
}
class FtpThread extends Thread{
Socket s;
long fileName = 0;
public FtpThread(Socket s){
this.s = s;
}
public void run(){
FileOutputStream out = null;
InputStream in = null;
File file = null;
do{
file = new File(""(fileName));
}while(file.exists());
try{
out = new FileOutputStream(file);
in= s.getInputStream();
byte[] buffer = new byte[1024*8];
int len = -1;
while((len=in.read(buffer)) != -1){
out.write(buffer, 0, len);
}
}catch(Exception e){
System.out.println("Error: "e.getMessage());
}finally{
try{
if(in != null) in.close();
if(out != null) out.close();
if(s != null) s.close();
System.out.println(s.getInetAddress().getHostAddress()" connect closed..");
}catch(Exception e){}
}
}
}
关于用JAVA的SOCKET传输文件点对点传输文件
/*
importjava.io.*;
importjava.net.*;
importjava.util.*;
*/
privateHttpURLConnectionconnection;//存储连接
privateintdownsize=-1;//下载文件大小,初始值为-1
privateintdowned=0;//文加已下载大小,初始值为0
privateRandomAccessFilesavefile;//记录下载信息存储文件
privateURLfileurl;//记录要下载文件的地址
privateDataInputStreamfileStream;//记录下载的数据流
try{
/*开始创建下载的存储文件,并初始化值*/
Filetempfileobject=newFile("h:\\webwork-2.1.7.zip");
if(!tempfileobject.exists()){
/*文件不存在则建立*/
tempfileobject.createNewFile();
}
savefile=newRandomAccessFile(tempfileobject,"rw");
/*建立连接*/
fileurl=newURL("");
connection=(HttpURLConnection)fileurl.openConnection();
connection.setRequestProperty("Range","byte=" this.downed "-");
this.downsize=connection.getContentLength();
//System.out.println(connection.getContentLength());
newThread(this).start();
}
catch(Exceptione){
System.out.println(e.toString());
System.out.println("构建器错误");
System.exit(0);
}
publicvoidrun(){
/*开始下载文件,以下测试非断点续传,下载的文件存在问题*/
try{
System.out.println("begin!");
Datebegintime=newDate();
begintime.setTime(newDate().getTime());
byte[]filebyte;
intonecelen;
//System.out.println(this.connection.getInputStream().getClass().getName());
this.fileStream=newDataInputStream(
newBufferedInputStream(
this.connection.getInputStream()));
System.out.println("size="this.downsize);
while(this.downsize!=this.downed){
if(this.downsize-this.downed262144){//设置为最大256KB的缓存
filebyte=newbyte[262144];
onecelen=262144;
}
else{
filebyte=newbyte[this.downsize-this.downed];
onecelen=this.downsize-this.downed;
}
onecelen=this.fileStream.read(filebyte,0,onecelen);
this.savefile.write(filebyte,0,onecelen);
this.downed=onecelen;
System.out.println(this.downed);
}
this.savefile.close();
System.out.println("end!");
System.out.println(begintime.getTime());
System.out.println(newDate().getTime());
System.out.println(begintime.getTime()-newDate().getTime());
}
catch(Exception e){
System.out.println(e.toString());
System.out.println("run()方法有问题!");
}
}
/***
//FileClient.java
import java.io.*;
import java.net.*;
public class FileClient {
public static void main(String[] args) throws Exception {
//使用本地文件系统接受网络数据并存为新文件
File file = new File("d:\\fmd.doc");
file.createNewFile();
RandomAccessFile raf = new RandomAccessFile(file, "rw");
// 通过Socket连接文件服务器
Socket server = new Socket(InetAddress.getLocalHost(), 3318);
//创建网络接受流接受服务器文件数据
InputStream netIn = server.getInputStream();
InputStream in = new DataInputStream(new BufferedInputStream(netIn));
//创建缓冲区缓冲网络数据
byte[] buf = new byte[2048];
int num = in.read(buf);
while (num != (-1)) {//是否读完所有数据
raf.write(buf, 0, num);//将数据写往文件
raf.skipBytes(num);//顺序写文件字节
num = in.read(buf);//继续从网络中读取文件
}
in.close();
raf.close();
}
}
//FileServer.java
import java.io.*;
import java.util.*;
import java.net.*;
public class FileServer {
public static void main(String[] args) throws Exception {
//创建文件流用来读取文件中的数据
File file = new File("d:\\系统特点.doc");
FileInputStream fos = new FileInputStream(file);
//创建网络服务器接受客户请求
ServerSocket ss = new ServerSocket(8801);
Socket client = ss.accept();
//创建网络输出流并提供数据包装器
OutputStream netOut = client.getOutputStream();
OutputStream doc = new DataOutputStream(
new BufferedOutputStream(netOut));
//创建文件读取缓冲区
byte[] buf = new byte[2048];
int num = fos.read(buf);
while (num != (-1)) {//是否读完文件
doc.write(buf, 0, num);//把文件数据写出网络缓冲区
doc.flush();//刷新缓冲区把数据写往客户端
num = fos.read(buf);//继续从文件中读取数据
}
fos.close();
doc.close();
}
}
*/
java 聊天 发送图片 文件传送要我的不?偶的带局域网搜索跟CS差不多 , 能从别的电脑上p2p下载文件功能很好很强大,就是没做聊天,你要加上充其量到不了150行代码 。要的话Hi我一下行 。
*******
哈哈哈,我懒了,没想改.楼上的哥哥很强大很耐心嘻嘻嘻~~
java聊天传输文件代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java socket 传输文件、java聊天传输文件代码的信息别忘了在本站进行查找喔 。
推荐阅读
- thinkphp模板找不到,thinkphp用的什么模板引擎
- u盘打印的东西怎么找回,u盘打印的东西怎么找回密码
- 公众号怎么用预约系统登录,公众号怎么用预约系统登录微信
- 火锅全程直播文案,火锅底料直播文案
- mysql怎么报错回滚 mysql数据回滚某个节点
- java冒泡排序代码优化,java冒泡排序代码简单
- 虚拟空间化,虚拟空间概念
- mysql中怎么储存文件 mysql存文章
- 小伙子拍摄的新电影叫什么,小伙回村拍电影