TCP通信编程-Java实现
客户端编程步骤:
建立网络连接
交换数据
关闭网络连接
服务器端编程步骤:
监听端口
获得连接
交换数据
关闭连接
主要理解一下以下几个类:
InetAddress类 该类的功能是代表一个IP地址,并且将IP地址和域名相关的操作方法包含在该类的内部。
ServerSocket类 用来给服务器端建立套接字,它的主要功能是等待来自网络上的“请求”,它可通过指定的端口来等大力连接的套接字。
Scoket类 客户机创建了Socket对象以后,会向指定的IP地址以及端口尝试连接。服务器会创建新的套接字与客户端套接字建立连接。
下面是C/S模式下的客户端与服务器端之间的通信源代码
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class ScoketServer {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket serverSocket=null;
Socket clientSocket=null;
DataInputStream in=null;
DataOutputStream out=null;
System.out.println("等待连接中。。。。");
serverSocket=new ServerSocket(4332);
clientSocket=serverSocket.accept();
in=new DataInputStream(clientSocket.getInputStream());
out=new DataOutputStream(clientSocket.getOutputStream());
InetAddress clientIP=clientSocket.getInetAddress();
System.out.println(clientIP);
System.out.println(clientSocket.getPort());
out.writeUTF("Welcome........");
String line=in.readLine();
while(line!="quit"){
System.out.println(line);
in.readLine();
}
}
}
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientSocket {
/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args
) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
Socket clientSocket;
DataInputStream in=null;
DataOutputStream out=null;
clientSocket=new Socket("127.0.0.1",4332);
in=new DataInputStream(clientSocket.getInputStream());
out=new DataOutputStream(clientSocket.getOutputStream());
out.writeUTF("我是客户机。。。。。。");
String str=null;
while(true){
str=in.readLine();
System.out.println(str);
}
}
}