第一块 客户端代码:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpIpTest {
public static void main(String[] args) {
int i = 9090;
String s = new String("127.0.0.1");
String content = new String("hello,I am client");
Client client = new Client(s, content, i);
client.start();
}
}
class Client {
int i; // 用于确定端口号
String content; // 用于确定通讯的字符串内容
String str = null; // 用于指定Ip地址
Socket socket = null;
OutputStream os = null;
// 构造器 分别用于初始化 IP地址, 传输字符串内容,端口号
Client(String str, String content, int i) {
this.str = str;
this.content = content;
this.i = i;
}
// 构造器 分别用于初始化 IP地址, 端口号
Client(String str, int i) {
this.str = str;
// this.content=content;
this.i = i;
}
// 自定义的客户端启动方法
void start() {
try {
socket = new Socket(InetAddress.getByName(str), i); // 创建客户端socket对象
os = socket.getOutputStream(); // 获得输出流
os.write(content.getBytes()); // 输出内容,因为并将content字符串转换为字节数组
socket.shutdownOutput(); // 传输完毕后告诉 自己传输完毕了
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) // 关闭稀有资源流
os.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
第二块 服务端代码
package Likeyong.com;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务端代码
public class ServerTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Server server = new Server(9090);
server.start();
}
}
class Server {
int i; // 用于确定端口号
ServerSocket ss = null;
InputStream is = null;
Socket s = null;
// 构造器
Server(int i) {
this.i = i;
}
void start() {
try {
ss = new ServerSocket(i);
s = ss.accept();
// ss.setSoTimeout(2500);
is = s.getInputStream();
int len;
byte[] b = new byte[20];
while ((len = is.read(b)) != -1) {
String s1 = new String(b, 0, len);
System.out.println(s1);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (s != null) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}