java 从零开始,学习笔记之基础入门<网络编程_带QQ模拟功能>(二十)(二)
ic class SDemo {
public static void main(String[] args)throws IOException {
ServerSocket server = new ServerSocket(9009);
//对Socket进行监听
Socket client = server.accept();
System.out.println("------------客户端链接成功-----------");
//服务器给客户端返回一句“链接服务器成功”
PrintWriter pw = null;
pw = new PrintWriter(client.getOutputStream());
pw.println("-----链接服务器成功------");
pw.flush();
while(true){
//服务端接收客户端输入的信息
BufferedReader br =null;
Reader reader =null;
reader = new InputStreamReader(client.getInputStream());
br = new BufferedReader(reader);
String str = br.readLine();
System.out.println("客户端说" +str);
//客户端说HELLO 服务端给客户端 hello girl!
pw.println("hello girl");
pw.flush();
if(str.equalsIgnoreCase("quit")){
System.out.println("下次再聊!");
pw.println("88!");
break;
}
}
}
}
Socket完成客户端到服务端的文件拷贝
package com.ibm.net.io;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
//文件的服务端
public static void main(String[] args) {
//创建服务器的套接字指定一个端口号最好端口号>9000
try {
ServerSocket server=new ServerSocket(9009);
//监听服务套接字上面的连接,如果有客户端连接进来,
//则创建一个客户端的socket
Socket client=server.accept();
System.out.println("客户进来了");
InetAddress ia = InetAddress.getLocalHost();
String ip = ia.getHostAddress();
System.out.println(ip);
// //客户端连接进来之后,服务端给客户端发送一个hello到客户端去
// PrintWriter pw=new PrintWriter(client.getOutputStream());
// pw.println("hello client");
// pw.flush();
// pw.close();
//将本地的一个文件通过字节流的形式传递到客户端上去
InputStream is=null;
OutputStream os=null;
//将读进来的文件字符流输出到客户端上去
os=client.getOutputStream();
is=new FileInputStream("d:\\张学友-想和你去吹吹风.mp3");
byte[] b=new byte[1024];
int len=0;
while((len=is.read(b))!=-1){
os.write(b, 0, len);
os.flush();
}
//关闭流
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.ibm.net.io;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class FileClient {
public static void main(String[] args) {
try {
//创建Socket指定服务器的地址和端口号
Socket client=new Socket("192.168.0.36",9009);
InputStream is=null;
//以输入流的形式接受服务器端发送的输出流
is=client.getInputStream();
OutputStream os=null;
//以输出流的形式将接受过来的输入流保存在磁盘上
os=new FileOut