TCP/IP通信协议是一种可靠地网络协议,他在通信的两端各建立一个socket,从而在通信的两端建立网络通信链路。Java对基于TCP协议的网络通信提供了良好的封装,java使用Socket对象来代表两端的通信端口,并通过Socket产生IO流来进行网络通信。
- 服务端代码,建立一个ServerSocket监听,用户监听客户端Socket的连接请求,每当接收到客户端Socket的请求时,服务端也对应产生一个Socket
package com.dalingjia.socket;
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) {
try {
//用指定的端口号来创建一个ServerSocket,端口号范围:0~65536
ss=new ServerSocket(5500);
System.out.println("服务器正常启动。。。。");
s=ss.accept();//阻塞方法,接受客户端socket请求
System.out.println("连接成功"+s.getRemoteSocketAddress());
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
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) {
e1.printStackTrace();
}finally {
try {
pw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客户端建立与指定IP地址,指定端口号的连接,并使用Socket获取输入流读取数据
package com.dalingjia.socket;
import java.io.*;
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) {
try {
//客户端通常使用Socket的构造器来连接到指定的服务器
Socket 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")){
break;
}
}
}catch (Exception e) {
e.printStackTrace();
}finally {
try {
pw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}