TCP通信 sever程序
package com.company;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class severSocket {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(1100);
System.out.println("服务器启动成功,等待用户接入。。。");
Socket client = server.accept();
System.out.println("有客户端链接进来,客户端IP"+client.getInetAddress());
InputStream input = client.getInputStream();
byte[] bt = new byte[1024];
int len = input.read(bt);
String data = new String(bt,0,len);
System.out.println("客户段发来的数据为:"+data);
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
client程序
package com.company;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
try {
Socket client = new Socket("127.0.0.1",1100);
System.out.println("链接成功!");
OutputStream out = client.getOutputStream();
String massage = "服务器,您好!我是客户端";
out.write(massage.getBytes(StandardCharsets.UTF_8));
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|