TCP编程步骤
使用SeverSocket建立一个简单的服务器步骤如下
第一步:创建一个SeverSocket对象ss。第二步:调用ss.accept()监听客户机
第三步:获得OutputStream和InputStream对象
第四步:服务器和客户机通过OutputStream和InputStream对象处理阶段
第五步:如果传输结束,通过调用相关流的close()以及Socket的close()关闭连接
使用Socket建立一个简单客户机
第一步:创建一个Socket对象s
第二步:Socket的getInputStream方法和getOutputStream方法分别用于获得与Socket相关联的InputStream和OutputStream的引用
第三步:客户机和服务器通过InputStream和OutputStream对象通信的处理阶段
第四步:如果传输结束,通过调用相关相关流的close(),以及Socket的close()关闭连接
此处插入TestTCP2
package inetadress;
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;
import org.junit.Test;
//TCP编程例二:客户端给服务端发送消息,服务端输出此信息到控制台上,同时发送“已收到信息”给客户端
public class TestTCP2 {
// 客户端
@Test
public void client() {
Socket socket = null;
OutputStream os = null;
InputStream is = null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"), 1888);
os = socket.getOutputStream();
os.write("我是客户端".getBytes());
//shutdownOutput():显示的告诉服务端发送完毕
socket.shutdownOutput();
is = socket.getInputStream();
byte[] b = new byte[20];
int len;
while ((len = is.read(b)) != -1) {
String str = new String(b, 0, len);
System.out.println(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Test
public void server() {
ServerSocket ss = null;
Socket s = null;
InputStream is = null;
OutputStream os = null;
try {
ss = new ServerSocket(1888);
s = ss.accept();
is = s.getInputStream();
byte[] b = new byte[20];
int len;
while ((len = is.read(b)) != -1) {
String str = new String(b, 0, len);
System.out.println(str);
}
os = s.getOutputStream();
os.write("我已收到你的情意".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (s != null) {
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}