TCP(socket)实例
服务器端:ServerSocketDemo.java
package com.tcp;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerSocketDemo {
/**
* @param args
*/
public static void main(String[] args) {
try {
ServerSocket serverSocket = null; //创建服务器端套接字
Socket clientSocket = null; //创建客户端套接字
String str = null;
//DataOutputStream与DataInputStream可以读取数据的java的基本类型
DataOutputStream out = null; //创建DataOutputStream类对象
DataInputStream in = null; //创建DataInputStream类对象
serverSocket = new ServerSocket(4331); //实例化套接字对象
System.out.println("等待与客户机的连接!!");
clientSocket = serverSocket.accept(); //接收客户端连接呼叫
//实例化DataInputStream对象
in = new DataInputStream(clientSocket.getInputStream());
out = new DataOutputStream(clientSocket.getOutputStream());
while (true) {
str = in.readUTF(); //读取客户放入连接中的信息
out.writeUTF("-----"+str); //返回给客户端的信息
System.out.println("服务器接收到:" + str);
Thread.sleep(1000); //线程休眠
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端:SocketDemo.java
package com.tcp;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
public class SocketDemo {
/**
* @param args
*/
public static void main(String[] args) {
String str = null;
Socket clientSocket; //创建客户端套接字
DataInputStream in = null; //创建DataInputStream对象
DataOutputStream out = null; //创建DataOutputStream对象
try {
clientSocket = new Socket("127.0.0.1",4331);
in = new DataInputStream(clientSocket.getInputStream());
out = new DataOutputStream(clientSocket.getOutputStream());
out.writeUTF("我是客户机!!"); //向流中写入信息
int i = 0;
//要先写才能读
while (true) {
str = in.readUTF(); //读取流中数据
out.writeUTF(i++ + ""); //向流中写入数据(是发送到服务器端的信息)
System.out.println("客户端收到:" + str); //输出信息
Thread.sleep(1000); //线程休眠
}
} catch (Exception e) {
e.printStackTrace();
}
}
}