首页 > 代码库 > tcp
tcp
服务端
/**
*
*/
package com.atguigu.exer;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import org.junit.Test;
/**
*方法说明
* @author shanghaitao
* @since 2017年5月2日
*/
public class Sserver {
public static void main(String[] args) {
}
@Test
public void testServer() {
System.out.println("这是服务端");
Socket s = null;
ServerSocket ss = null;
InputStream is = null;
OutputStream os = null;
try {
ss = new ServerSocket(9999);
s = ss.accept();
String str = null;
byte [] b = new byte[10];
int len ;
is = s.getInputStream();
while((len = is.read(b))!=-1){
str += new String(b, 0, len);
System.out.println(str);
}
os = s.getOutputStream();
os.write("我已收到你的信息".getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
if(os!=null){
try {
os.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if(is!=null){
try {
is.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if(s!=null){
try {
s.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if(ss!=null){
try {
ss.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
}
客户端
/**
*
*/
package com.atguigu.exer;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import org.junit.Test;
/**
*方法说明
* @author shanghaitao
* @since 2017年5月2日
*/
public class Cllient {
public static void main(String[] args) {
}
@Test
public void TestClient() {
System.out.println("这是客户端");
Socket socket = null;
InputStream is = null;
OutputStream os = null;
try {
socket = new Socket(InetAddress.getLocalHost(), 9999);
is = socket.getInputStream();
os = socket.getOutputStream();
os.write("我是客户端".getBytes());
socket.shutdownOutput();
String str = null;
byte b [] = new byte[10];
int len ;
while((len = is.read(b))!=-1){
str += new String(b,0,len) ;
System.out.println(str);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(is !=null){
try {
is.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if(os !=null){
try {
os.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if(socket !=null){
try {
socket.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
}
输出
这是客户端
null我已收到你
null我已收到你的信息
这是服务端
null我是客户端
tcp