---
title: "简单聊天室如何传输文本和聊天"
author: "胖好汉"
date: "2014-07-20T12:47:08Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-07-20T12:46:54Z"
id: 2092700
url: "https://panghaohan.iteye.com/blog/2092700"
---

对于用户来说，出现在他们眼前的是客户端，一般来说，服务端是看不见的，所以说，服务端就是起到了一个传输与连接各个客户端的作用。那么在传送文件和聊天内容时，要怎么书写服务端呢？下面来看：

 

服务端

       无论是什么服务端，至少是需要等待客户端接入的，所以这段代码是大家都很熟悉的

```
public void setServer(int port){
try {
			ServerSocket ss = new ServerSocket(port);
			while(true){
				Socket s = ss.accept();
				process(s);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
```

        在等待客户机接入后，ss.accept()；获取输入输出流，这里注意使用DataOutputStream来方便读取原始类型的流。发送方发送消息时，必须按照顺序和格式将数据依次写入输出流对象中。 服务器端在读取时：  
       （１）首先读取一个 int 型数据，即消息的总长度。  
       （２）再读取一个 byte 数据，即消息类型值，根据其值，判定这条消息是文本还是文件。  
       （３）如果消息类型值是 1,则认为是文本聊天消息。然后读取一个 int 型，作为接收方的号  
码。根据协议的规则，总长度=(消息长度字段的 4 个字节)+类型的 1 个字节+接收号码的 4 个字节+  
消息内容字节长度，余下的长度，则是聊天内容的字节个数，假设是 MsgLen；最后读取 MsgLen  
个字节，组成一个字符串，就是用户聊天的内容。  
       （４）如果类型是 2，则是文件消息。读取接收方号码后，再读取 256 个字节组成一个字符串  
当做文件名。如果发送时文件名是abc.gif，长度还是 256 字节。因为根据协议，这个字段的固定  
长度是 256 个字节。 发送时，不足256 字节则补足二进制 0（‘\\0’）。 对方接收后，只要去掉所读  
取字节转成的字符串末尾的空格，得到的就是发送的文件名。 最后，用总长度减掉前面每个字段的  
长度，余下的数字就是要读取的文件内容的字节长度，将这些字节读入，存放到文件中，即完成  
了文件的传送。

```
protected void startFile(Socket s) {
		byte[] bt = null ;
		int len =0;
		DataInputStream dis ;
		FileOutputStream fos ;
		String filePath="F:/c盘内容/Desktop/xin.mp4" ;
		try {
			filePath=s.getInputStream().toString();
			System.out.println(filePath);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			dis=new DataInputStream (s.getInputStream());
			//Flie f = new File();
			fos = new FileOutputStream(new File("F:/c盘内容/Desktop/"+filePath));
			bt=new byte[1024];
			while((len=dis.read(bt,0,bt.length))>0){
				fos.write(bt, 0, len);
				fos.flush();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
```

         完成了服务器端后就是客户端了，这一部分不是十分的难，所以，代码出来吧~！ 

```
private void setUP(int port) throws IOException {
		FileInputStream fis =null;
		DataOutputStream dos = null;
		byte[] bt =null;
		int len =0;
		Socket socket=null;
		
		File f = new File("G:/学习资料/two.avi");
	
		try {
			
			 File file = new File("G:/六维/8分钟腹肌锻炼第1级.avi"); //要传输的文件路径   
	         long l = f.length();
	         double sumL=0;
	         String str = file.getName();
	         
	         socket = new Socket();    
	            socket.connect(new InetSocketAddress("127.0.0.1", 9090));  
	            dos = new DataOutputStream(socket.getOutputStream());  
	            fis = new FileInputStream(file);        
	            bt = new byte[2048];  
	            
	            bt=str.getBytes();
	            dos.write(bt);
	            dos.flush();
	            System.out.println(str);
	            
	            while ((len = fis.read(bt, 0, bt.length)) > 0) {
	            	sumL+=len;
	            	//System.out.println("已传输："+((sumL/l)*100)+"%"); 
	                dos.write(bt, 0, len);  
	                dos.flush();  
	            }   
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{    
	         if (dos != null)  
	             dos.close();  
	         if (fis != null)  
	             fis.close();     
	         if (socket != null)  
	             socket.close();      
	     }  
		
	}
```