Socket 复习小案例
服务端
package com. test. tcp ;
import java. io. * ;
import java. net. ServerSocket ;
import java. net. Socket ;
import java. text. SimpleDateFormat ;
import java. util. Date ;
public class Server extends Thread {
private final static String ip = "localhost" ;
private final static int port = 8889 ;
private static ServerSocket serverSocket = null ;
private static Socket socket = null ;
public Server ( ) {
try {
serverSocket= new ServerSocket ( port) ;
serverSocket. setSoTimeout ( 10000 ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
@Override
public void run ( ) {
System . out. println ( "等待客户端...." ) ;
String s = null ;
InputStream in = null ;
Date d1 = new Date ( ) ;
FileWriter fw = null ;
SimpleDateFormat sdf = new SimpleDateFormat ( "yyyyMMdd" ) ;
String path = "H:\\" + sdf. format ( d1) ;
File file = new File ( path) ;
try {
fw = new FileWriter ( file, true ) ;
while ( true ) {
socket = serverSocket. accept ( ) ;
if ( socket != null ) {
in = socket. getInputStream ( ) ;
byte [ ] buf = new byte [ 1024 ] ;
int len = 0 ;
while ( ( len = in. read ( buf) ) != - 1 ) {
if ( file. exists ( ) ) {
fw. write ( new String ( buf, 0 , len) ) ;
fw. write ( "\r\n" ) ;
fw. flush ( ) ;
} else {
file. mkdir ( ) ;
fw. write ( new String ( buf, 0 , len) ) ;
fw. write ( "\r\n" ) ;
fw. flush ( ) ;
}
}
}
in. close ( ) ;
socket. close ( ) ;
serverSocket. close ( ) ;
break ;
}
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
客户端
package com. test. tcp ;
import java. io. IOException ;
import java. io. OutputStream ;
import java. net. Socket ;
public class Client extends Thread {
private final static String ip = "localhost" ;
private final static int port = 8889 ;
private static Socket socket = null ;
public Client ( ) {
try {
socket = new Socket ( ip, port) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
@Override
public void run ( ) {
OutputStream out = null ;
int i = 0 ;
while ( true ) {
String string = "你好!" ;
try {
out = socket. getOutputStream ( ) ;
out. write ( string. getBytes ( ) ) ;
i++ ;
try {
Thread . sleep ( 3000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
if ( i > 10 ) {
out. close ( ) ;
socket. close ( ) ;
break ;
}
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
}
测试
package com. test. tcp ;
public class Main {
public static void main ( String [ ] args) {
Server server = new Server ( ) ;
server. start ( ) ;
Client client = new Client ( ) ;
client. start ( ) ;
}
}
备注:代码中路径换成自己的