(一)服务器端的程序
import java.net.Socket;
import java.util.Scanner;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
public class Server {
public static void main(String[] args) throws IOException{
ServerSocket ss = new ServerSocket(1010);
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("-----服务器读来自客户端的信息-----");
Socket s = ss.accept();
InputStream is = s.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
int fk = 0;
while ((len = is.read(bytes)) != -1) {
System.out.println(new String(bytes, 0, len));
fk = len;
}
System.out.println("-----服务器向客户端写的信息-----");
OutputStream os = s.getOutputStream();
String str = fk + "";
System.out.println(fk);
os.write(str.getBytes());
os.close();
is.close();
}
}
}
(二)客户端的程序
2.1 持久连接版本
import java.net.Socket;
import java.util.Scanner;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
public class Client {
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
String str = "";
System.out.println("客户端发送消息:");
while((str = sc.next()) != null){
Socket s = new Socket("localhost", 1010);
OutputStream os = s.getOutputStream();
os.write(str.getBytes());
s.shutdownOutput();
System.out.println("客户端接收消息:");
InputStream is = s.getInputStream();
byte[] btr = new byte[1024];
int len = 0;
while ((len = is.read(btr)) != -1) {
System.out.println(new String(btr, 0, len));
}
is.close();
os.close();
System.out.println("客户端发送消息:");
}
}
}
2.2 非持久连接版本
import java.net.Socket;
import java.util.Scanner;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
public class Client {
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
String str = "";
System.out.println("-----客户端向服务器写的信息-----");
while((str = sc.next()) != null){
Socket s = new Socket("localhost", 1010);
OutputStream os = s.getOutputStream();
os.write(str.getBytes());
s.shutdownOutput();
System.out.println("-----客户端读来自服务器的信息-----");
InputStream is = s.getInputStream();
byte[] btr = new byte[1024];
int len = 0;
while ((len = is.read(btr)) != -1) {
System.out.println(new String(btr, 0, len));
}
is.close();
os.close();
System.out.println("-----客户端向服务器写的信息-----");
}
}
}