TCP网络编程
1 流程
2 服务端代码:
package cn.jingshan.tcp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author yuajings
* @desc TCP服务端
*/
public class TCPServer {
public static void main(String[] args) throws IOException {
//创建socket监听服务
ServerSocket listen = new ServerSocket(5050);
//建立连接
Socket server = listen.accept();
//通信
InputStream in = server.getInputStream();
OutputStream out = server.getOutputStream();
//接收消息
char c = (char)in.read();
System.out.println("收到:" + c);
//发送消息
out.write('s');
//关闭连接
out.close();
in.close();
server.close();
listen.close();
}
}
3 客户端代码:
package cn.jingshan.tcp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* @author yuajings
* @desc TCP客户端
*/
public class TCPClient {
public static void main(String[] args) throws IOException {
//创建Socket
Socket client = new Socket("127.0.0.1", 5050);
//通信
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
//发送消息
out.write('c');
//接收消息
char c = (char)in.read();
System.out.println("收到:" + c);
//关闭连接
out.close();
in.close();
client.close();
}
}