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,i);
// Client client = new Client(s, content, i);
Server server = new Server(i);
//System.out.println("11111111111111111111");
server.start();
client.start();
//System.out.println("211111111111111111111");
}
}
class Client {
String str = null;
String content;
int i;
Socket socket = null;
OutputStream os = null;
// Client(String str, String content, int i) {
// this.str = str;
// this.content = content;
// this.i = i;
//
// }
Client(String str, int i) {
this.str = str;
// this.content=content;
this.i = i;
}
void start() {
try {
socket = new Socket(InetAddress.getByName(str),i);
os = socket.getOutputStream();
os.write(str.getBytes());
socket.shutdownOutput();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException 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();
}
}
}
}
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();
}
}
}
}
}
无法进行通讯
下面是日志截图