[java]代码库
package com.lzcc.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
try {
//1.创建socket,指定服务器地址和端口
Socket socket = new Socket("localhost",8888);
//2.获取输出流,向服务器端发送信息
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.write("hello nice to meet you ");
pw.flush();
socket.shutdownOutput();
//获取输入流,读取服务器端响应的信息
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String info ;
while((info = br.readLine())!=null){
System.out.println("我是客户端------服务器说:"+info);
}
br.close();
is.close();
pw.close();
os.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.lzcc.socket;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
Socket socket=null;
//记录客户端数量
int count=0;
System.out.println("服务器启动,等待客户端连接");
//循环侦听客户端请求
while(true){
socket = serverSocket.accept();
//创建一个新的线程
ServerThread serverThread = new ServerThread(socket);
//启动线程,执行与客户端的通信
serverThread.start();
System.out.println("已连接");
count++;
System.out.println("已经连接了"+count+"个");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
[代码运行效果截图]
[源代码打包下载]