关于java网络编程的实例代码
服务器端的写法
package com.chinasofti.corejava.ch22;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
private static BufferedReader br=null;
private static PrintWriter pw=null;
private static ServerSocket ss;
private static Socket s;
static Scanner scanner=new Scanner(System.in);
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
ss=new ServerSocket(5500);
System.out.println("服务器正常启动。。。。");
//调用ServerSocket的accept方法,可以接受客户端的请求,并返回当前的Socket对象
s=ss.accept();//阻塞方法
System.out.println("连接成功"+s.getRemoteSocketAddress());
//获得基于Socket的输入流
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
//获得基于Socket的输出流
pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
while(true){
String string=br.readLine();
System.out.println("Server读到:"+string);
System.out.println("Server端请输入:");
String str=scanner.next();
pw.println(str);
pw.flush();
if(str.equals("exit")){
break;
}
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
pw.close();
br.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
客户端的写法
package com.chinasofti.corejava.ch22;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class Client {
private static PrintWriter pw=null;
private static BufferedReader br=null;
private static Socket s;
static Scanner scanner=new Scanner(System.in);
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
s=new Socket(InetAddress.getLocalHost(),5500);
pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
while(true){
System.out.println("Client端请输入:");
String str = scanner.next();
pw.println(str);
pw.flush();
String string=br.readLine();
System.out.println("Client读到:"+string);
if(str.equals("exit")){
s.close();
break;
}
}
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
br.close();
pw.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}