利用socket传输对象

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_34721505/article/details/73468799

一、创建用户类User;

package socket;

import java.io.Serializable;
/**
 * 用户类
 */
public class User implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7965470946723147485L;
	private String id;
	private String username;
	private String password;
	
	public User() {
	}

	public User(String id, String username, String password) {
		this.id = id;
		this.username = username;
		this.password = password;
	}
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

二、创建服务端ServerSocket;

package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
/**
 * 基于TCP协议的Socket通信,传输对象
 * 服务器端
 */
public class Server {
	static ServerSocket serverSocket ;
	static Socket socket;
	static InputStream is;
	static StringBuffer sb;
	static InputStreamReader isr;
	static OutputStream os;
	
	public static void main(String[] args) {
		try {
			//1、创建一个服务器端Socket,即ServerSocket,指定绑定的端口,并监听此端口
			serverSocket = new ServerSocket(9999);
			//2、调用accept()方法开始监听,等待客户端的连接 
			socket = serverSocket.accept();
			//3、获取输入流,并读取客户端信息 
			is = socket.getInputStream();
			//4、转化为对象输入流
			ObjectInputStream ois = new ObjectInputStream(is);
			User user = (User) ois.readObject();
			//5、返回消息给客户端
			os = socket.getOutputStream();
			if(user.getUsername().equals("admin")){
				System.out.println("我是服务器,客户端当前登录用户是:"+user.getUsername());
				//返回登录成功的信息给客户端
				os.write( ("欢迎你," + user.getUsername()).getBytes() );
				os.flush();
			}else{
				//返回登录失败的信息给客户端
				System.out.println("登录失败");
				os.write( (user.getUsername() + "登录失败").getBytes() );
				os.flush();
			}
			//关闭输入流
			//socket.shutdownInput();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			try {
				if( os != null){
					os.close();
				}
				if(isr != null){
					isr.close();
				}
				if(is != null){
					is.close();
				}
				if(socket != null){
					socket.close();
				}
				if(serverSocket != null){
					serverSocket.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}


三、创建客户端Socket;

package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
	static Socket socket;
	static OutputStream os;
	static InputStream is ;
	static InputStreamReader isr;
	static BufferedReader br;
	
	public static void main(String[] args) {
		try {
			//1、创建客户端Socket,指定服务器地址和端口 
			socket = new Socket("127.0.0.1", 9999);
			//2、获取输出流,向服务器端发送信息 
			os =socket.getOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(os);
			oos.writeObject(new User("1","admin","admin"));
			oos.flush();
			//3、获取服务器端返回的信息
			is = socket.getInputStream();
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr);
			String data = null;
			StringBuffer sb = new StringBuffer();			
			while( (data = br.readLine()) != null ){
				sb.append(data);
			}
			System.out.println("服务器端返回的信息是:" + sb);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(br != null)
					br.close();
				if(isr != null)
					isr.close();
				if(os != null)
					os.close();
				if(is != null)
					is.close();
				if(socket != null)
					socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}


四、测试结果;

客户端:服务器端返回的信息是:欢迎你,admin

服务端:我是服务器,客户端当前登录用户是:admin

五、总结

1、对于同一个socket,如果关闭了输出流,则与该输出流关联的socket也会被关闭,所以一般不用关闭流,直接关闭socket即可;

2、使用TCP协议传输对象时,对象必须序列化;

展开阅读全文

利用socket进行文件分割传输

04-13

rn一个窗体同时作为发送和接收端,所以client的ip已经设好127.0.0.1,而且端口也已经设好。一些变量设为静态。rnrn我使用它传一个图片,接收下来的图片有重叠。但不调试发现执行一次ClientWrite,接收方执行ServerClientRead不是一次,而是两次。rnrn我真搞不明白了。所以那位高手做过诸如此类的程序,请指教!rnrn具体程序如下:rnrn/---------------------------------------------------------------------------rnrn#include rn#pragma hdrstoprnrn#include "UCommunicate.h"rn//---------------------------------------------------------------------------rn#pragma package(smart_init)rn#pragma resource "*.dfm"rnrnstatic int final,emod=0,hui=0,x=0,a=0,i=0;rnrnTMainFrm *MainFrm;rn//---------------------------------------------------------------------------rn__fastcall TMainFrm::TMainFrm(TComponent* Owner)rn : TForm(Owner)rnrnrn//---------------------------------------------------------------------------rnvoid __fastcall TMainFrm::ClientWrite(TObject *Sender,rn TCustomWinSocket *Socket)rnrn void *p[20000];rn static long k=20000;rn static long bmpsize,c,mod;rn static TMemoryStream* pms = new TMemoryStream();rn if(hui==0)rn pms->LoadFromFile(filename);hui++; //装入要发送的文件。rn bmpsize=pms->Size; //计算文件的大小(字节)rn c=(int)bmpsize/k; //分割文件为crn mod=bmpsize%k; //分割后于下的字节数rn emod=mod; //使mod在整个程序都可访问rn rn if(iPosition=x; //改变内存流读取指针rn pms->ReadBuffer(p,k); //把内存流读入缓冲区rn x=x+k;rn Client->Socket->SendBuf(p,k); //将分割的文件发送rn i++ ;rn rn elsern rn final++;rn pms->Position=x;rn pms->ReadBuffer(p,mod); //发送最后mod个字节后,发送完毕rn Client->Socket->SendBuf(p,mod);rnrnrn rnrnrnrn//---------------------------------------------------------------------------rnvoid __fastcall TMainFrm::Button1Click(TObject *Sender)rnrn if(OpenDialog1->Execute())rn rn filename = OpenDialog1->FileName;rn Label1->Caption="选择图片成功";rn hui=0; a=0; final=0;rn x=0; i=0;rn rnrn//---------------------------------------------------------------------------rnvoid __fastcall TMainFrm::ClientConnect(TObject *Sender,rn TCustomWinSocket *Socket)rnrn Label1->Caption="ok";rnrn//---------------------------------------------------------------------------rnvoid __fastcall TMainFrm::ServerClientRead(TObject *Sender,rn TCustomWinSocket *Socket)rnrn static TMemoryStream* qms = new TMemoryStream();rn void *z[20000]; //定义缓冲区大小rnrn if(final!=1)rn rn Socket->ReceiveBuf(z,20000); //接收SOCKET中的数据流rn qms->Position=a;rn qms->WriteBuffer(z,20000); //写入缓冲区 rn a=a+20000; //改变内存流指针rn Client->Active=false; //每次发送前要判断网络是否畅通rn Client->Port=8888; //联接远程计算机,如果成功则 发送,否则等待rn Client->Active=true;rn rn else //接收最后emod个字节。rn rn qms->WriteBuffer(z,emod);rn qms->SaveToFile("g:\\ok.bmp");rn Label1->Caption="successful";rn qms->Position=0;rn Image1->Picture->Bitmap->LoadFromStream(qms);rn rnrnrn//---------------------------------------------------------------------------rnrnvoid __fastcall TMainFrm::Button2Click(TObject *Sender)rnrn Client->Active=false;rn Client->Port=8888;rn Client->Active=true;rn rnrn//---------------------------------------------------------------------------rn 论坛

利用SOCKET传输文件的问题

05-17

我写了一个文件传输的小软件,利用WinSock进行文件的传输。但有一些问题,代码如下:rnrn服务器端:rn[code=C/C++]rn//发送文件rnDWORD dwRead;rnBOOL bOk;rnchar sendbuf[1024*4]; //每次传送4KB数据rnrnHANDLE hFile=CreateFile(strFileName,GENERIC_READ,0,0,OPEN_EXISTING,rn FILE_ATTRIBUTE_NORMAL,0);//创建文件句柄rnwhile(1)rnrn ZeroMemory(sendbuf,1024*4);rn bOk=ReadFile(hFile,sendbuf,1024*4,&dwRead,NULL);//读取文件rn if(bOk==FALSE)rn rn break;rn rn else if(dwRead==0)rn rn AfxMessageBox("文件发送完毕");rn break;rn rn elsern rn int nSend=::send(socket,sendbuf,dwRead,0);rn if(nSend<=0)rn rn break;rn rn rnrnCloseHandle(hFile);rn[code]rnrnrn客户端:rn[code=C/C++]rnchar recvbuf[1024*4];rnint read;rnDWORD dwWrite;rnBOOL bOk;rnHANDLE hFile=CreateFile(strFileFullName,GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);rnwhile(1)rnrn read=-1;rn ZeroMemory(recvbuf,1024*4);rn read=::recv(connectionSocket,recvbuf,1024*4,0); //接收数据rn if(read<=0)rn break;rn bOk=WriteFile(hFile,recvbuf,read,&dwWrite,NULL);//写文件rn rn if(bOk==FALSE)rn rn MessageBox(_T("文件写入失败!"),_T("文件下载失败"),MB_OK|MB_ICONERROR);rn break;rn rnrnAfxMessageBox(_T("文件下载完成"));rnCloseHandle(hFile);rn[/code]rnrnrn问题主要是在客户端中的while循环不会跳出来,也就是不会弹出文件下载完成的对话框!但服务器端会提示文件传送完毕,比知道原因何在?rn注:上述代码都在线程使用,其中MessageBox函数是我刚才修改的,方便大家阅读! 论坛

通过Socket传输对象的问题

06-14

想通过套接字传输对象,但是运行后总是出现阻塞的现象rn如果只发送Object不让服务器返回,客户端也不接收的话可以正常运行,一旦返回就出现阻塞现象rn在网上查了两天了,有网友说要注意ObjectInputStream和ObjectOutputStream的创建顺序,我也试了,还是不行rn在线等各位解答,这个问题搞定,项目就可以正常进行了rn下面是代码:rn[code=Java]import java.io.*;rnimport java.net.Socket;rnimport java.net.ServerSocket;rnrnpublic class ServerPointrn private static ServerSocket server; rn rn public ServerPoint()rn try rn server=new ServerSocket(8088);rn System.out.println ("服务器已经启动......");rn while(true)rn Socket socket=server.accept();rn ServerThread st=new ServerThread(socket);rn Thread thread=new Thread(st);rn thread.start();rn rn rn catch (Exception ex) rn ex.printStackTrace();rn rn rn public static void main(String[] args)rn new ServerPoint();rn rn[/code]rnrn[code=Java]import java.io.*;rnimport java.net.Socket;rnrnpublic class ServerThread implements Runnablern rn private Socket socket;rn rn public ServerThread(Socket socket)rn this.socket=socket; rn rn rn public void run()rn try rn //服务器端先读后写rn ObjectInputStream objin=new ObjectInputStream(new BufferedInputStream(socket.getInputStream())); rn ObjectOutputStream objout=new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));rn //读取客户端发送过来的对象rn Student s=(Student)objin.readObject();rn System.out.println (s.getName()+" "+s.getScore());rn objout.writeObject(s);rn objout.flush();rn rn objin.close();rn objout.close();rn socket.close();rn rn catch (Exception ex) rn ex.printStackTrace();rn rn rn[/code]rnrn[code=Java]import java.awt.*;rnimport java.awt.event.*;rnimport java.io.*;rnimport java.net.Socket;rnrnpublic class ClientPoint extends Framern private Panel center,buttom;rn private Button btnSend,btnReset;rn private TextField txtName,txtScore;rn private Label lblName,lblScore;rn rn public ClientPoint()rn super("客户端");rn center=new Panel();rn buttom=new Panel();rn btnSend=new Button("Send");rn btnReset=new Button("Reset");rn txtName=new TextField();rn txtScore=new TextField();rn lblName=new Label("姓名: ");rn lblScore=new Label("成绩: ");rn center.setLayout(new GridLayout(2,2));rn center.add(lblName);center.add(txtName);rn center.add(lblScore);center.add(txtScore);rn buttom.add(btnSend);rn buttom.add(btnReset);rn btnSend.addActionListener(new ActionListener()rn public void actionPerformed(ActionEvent e)rn processSend();rn rn );rn this.setLayout(new BorderLayout());rn this.add(center,BorderLayout.CENTER);rn this.add(buttom,BorderLayout.SOUTH);rn this.setSize(300,100);rn this.show();rn rn rn private void processSend()rn //获得用户输入的信息rn String name=txtName.getText();rn Integer score=new Integer(txtScore.getText());rn Student s=new Student(name,score);rn try rn //发送对象到服务器,先写后读rn Socket socket=new Socket("127.0.0.1",8088);rn ObjectOutputStream objout=new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));rn ObjectInputStream objin=new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));rn objout.writeObject(s);rn objout.flush();rn Student stu=(Student)objin.readObject();rn System.out.println (stu.getName()+" "+stu.getScore()); rn objout.close();rn socket.close();rn rn catch (Exception ex) rn ex.printStackTrace();rn rn rn rn public static void main(String[] args)rn new ClientPoint();rn rnrnrn[/code]rnStudent类已经序列化了,因为比较简单,这里就不贴出来了rn期待各位的答复,谢谢 论坛

socket 传输对象,出现ClassCastException

04-08

[b][color=#FF00FF]客户端的Message类[/color][/b]rnpackage com.client.comm;rnrnimport java.io.Serializable;rnimport java.net.Socket;rnimport java.util.ArrayList;rnrnpublic class Message implements Serializable rn rn private ArrayList list;rn //get和set方法rn ..........rnrnrn[b][color=#FF00FF]服务器端的Message类[/color][/b]rnpackage com.server.comm;rnrnimport java.io.Serializable;rnimport java.net.Socket;rnimport java.util.ArrayList;rnrnpublic class Message implements Serializable rn rn private ArrayList list;rn //get和set方法rn .................rnrnrnrn[b][size=16px][color=#FF00FF]客户端代码(下面这段代码出错)[/color][/size][/b]rnpublic class ClientThread implements Runnable rnrn // 定义主机地址rn String host = "127.0.0.1";rn // 定义端口号rn int port = 2160;rnrn Socket socket;rn ObjectInputStream in;rn ObjectOutputStream out;rnrn rn ClientThread(Socket socket)rn this.socket=socket;rn try rn out = new ObjectOutputStream(socket.getOutputStream());rn in = new ObjectInputStream(socket.getInputStream());rn rn catch (Exception e) rn e.printStackTrace();rn rn rnrn public void run() rn Message message = new Message();rn while (true) rnrn if (socket.isClosed()) rn break;rn rn try rn [color=#FF0000] message = (Message) in.readObject();[/color]rn rn catch (Exception e) rn e.printStackTrace();rn rn rnrnrnrnrnjava.lang.ClassCastException: com.server.comm.Message cannot be cast to com.client.comm.Messagern at com.client.model.ClientThread.run(ClientThread.java:48)rn at java.lang.Thread.run(Thread.java:619) 论坛

没有更多推荐了,返回首页