62,620
社区成员
发帖
与我相关
我的任务
分享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 java.util.Scanner;
public class SocketTest {
public static void main(String[] args) {
final SocketTest st = new SocketTest();
new Thread(new Runnable(){
@Override
public void run() {
st.服务端();
}
}).start();
new Thread(new Runnable(){
@Override
public void run() {
st.客户端();;
}
}).start();
}
public void 客户端() {
Socket socket = null;
OutputStream os = null;
Scanner scanner = null;
InputStream is = null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"), 7032);
os = socket.getOutputStream();
System.out.print("请输入英文字母:");
scanner = new Scanner(System.in);
String str = scanner.next();
os.write(str.getBytes());
os.flush();
is = socket.getInputStream();
byte[] b = new byte[10];
int len;
while ((len = is.read(b)) != -1) {
String str1 = new String(b, 0, len);
System.out.print(str1);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 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 (scanner != null) {
scanner.close();
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void 服务端() {
ServerSocket ss = null;
Socket s = null;
InputStream is = null;
OutputStream os = null;
try {
ss = new ServerSocket(7032);
s = ss.accept();
is = s.getInputStream();
os = s.getOutputStream();
byte[] b = new byte[10];
int len;
String str = null;
while ((len = is.read(b)) != -1) {
String str1 = new String(b, 0, len);
str += str1;
String zb = str.toUpperCase();
os.write(zb.getBytes());
os.flush();
}
} 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 (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();
}
}
}
}
}