Javaソケット通信
昨日、ある仲間がsocket通信に悩んでいたので、簡単にdemoで彼の疑問を解決しました.
Serverエンド
Serverエンド
package com.ustc;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static Socket soc = null;
static BufferedReader bufferedReader= null;
static PrintStream printStream = null;
public static BufferedReader getBufferedReader() throws IOException{
if(bufferedReader == null){
Socket soc = getsock();
bufferedReader = new BufferedReader(new InputStreamReader(soc.getInputStream()));
}
return bufferedReader;
}
public static PrintStream getPrintStream() throws IOException{
if(printStream == null){
Socket soc = getsock();
printStream = new PrintStream(soc.getOutputStream());
}
return printStream;
}
public static void main(String[] args) {
try {
soc = getsock();
}
catch (IOException e){
e.printStackTrace();
}
accept();
send("server");
}
public static Socket getsock() throws IOException{
if(soc==null) {
ServerSocket serverSocket = new ServerSocket(12345);
return soc = serverSocket.accept();
}
else{
return soc;
}
}
public static void accept(){
new Thread() {
@Override
public void run() {
try{
System.out.println(" "+getBufferedReader().readLine());
}
catch(IOException e) {
System.out.println(" ");
}
}
}.start();
}
public static void send(String str){
new Thread() {
@Override
public void run() {
try{
getPrintStream().println(str);
System.out.println(" "+str);
}
catch(IOException e) {
System.out.println(" ");
}
}
}.start();
}
}
Client
package com.ustc;
import java.io.*;
import java.net.Socket;
public class client {
static Socket soc = null;
static BufferedReader bufferedReader = null;
static PrintStream printStream;
public static Socket getSoc() throws IOException{
if(soc ==null) {
soc = new Socket("127.0.0.1", 12345);
}
return soc;
}
public static BufferedReader getBufferedReader() throws IOException{
if(bufferedReader == null){
bufferedReader = new BufferedReader(new InputStreamReader(getSoc().getInputStream()));
return bufferedReader;
}
return bufferedReader;
}
public static PrintStream getPrintStream() throws IOException{
if(printStream == null){
printStream = new PrintStream(getSoc().getOutputStream());
}
return printStream;
}
public static void main(String[] args) {
try{
soc = getSoc();
}
catch (IOException e){
e.printStackTrace();
}
accept();
send("client");
}
public static void accept(){
new Thread(){
@Override
public void run() {
try {
System.out.println(" "+getBufferedReader().readLine());
}
catch (IOException e){
e.printStackTrace();
}
}
}.start();
}
public static void send(String str){
new Thread(){
@Override
public void run() {
try {
getPrintStream().println(str);
System.out.println(" "+str);
}
catch (IOException e){
e.printStackTrace();
}
}
}.start();
}
}
,